package test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Main2 {
public static void main(String[] args) {
//Map<String, String> map = new ConcurrentHashMap<>();
//报错:Exception in iterator thread: java.util.ConcurrentModificationException
Map<String, String> map = new HashMap<>();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
Thread iteratorThread = new Thread(() -> {
try {
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println("Iterating key: " + key);
Thread.sleep(100);
}
} catch (Exception e) {
System.out.println("Exception in iterator thread: " + e);
}
});
Thread modifyThread = new Thread(() -> {
try {
Thread.sleep(150);
map.put("4", "four");
System.out.println("Added key: 4");
} catch (Exception e) {
System.out.println("Exception in modify thread: " + e);
}
});
iteratorThread.start();
modifyThread.start();
}
}
HashMap执行结果,报错,当前修改异常:ConcurrentModificationException
ConcurrentHashMap执行结果,正常不报错