【发布时间】:2016-07-15 19:38:27
【问题描述】:
我有以下代码:
static final Map<String, String> map = Collections.synchronizedMap(new HashMap());
public static void main(String[] args) throws InterruptedException {
map.put("1", "1");
map.put("2", "2");
new Thread(new Runnable() {
@Override
public void run() {
for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
System.out.println("after iterator");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
Thread.sleep(50);
map.remove("1");
System.out.println("removed");
}
它产生java.util.ConcurrentModificationException
如何避免?
【问题讨论】:
-
使 run 方法同步.. 或者您可以使用并发 hashmap 。 docs.oracle.com/javase/7/docs/api/java/util/concurrent/…
-
看起来和你之前的问题基本一样:stackoverflow.com/questions/36228084/…
-
使用
ConcurrentHashMap。.synchronizedMap()中的迭代器未同步。
标签: java dictionary iterator concurrentmodification