我有以下代码:
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
我怎样才能避免呢?
3条答案
按热度按时间nimxete21#
除非使用迭代器,否则在迭代集合时不能从集合中移除元素。使用iterator.remove()方法
gz5pxeao2#
如果你想迭代
Collections.synchronizedMap
必须显式同步迭代:vdgimpew3#
你可以用
static final Map<String, String> map = new ConcurrentHashMap<>();
```static final Map<String, String> map = new ConcurrentHashMap<>();
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();
}
}