HashMap在并发下线程不安全, public class ThreadDemo01 { public static void main(String[] args) { //演示HashMap Map<String, String> map = new HashMap<>(); for (int i = 0; i < 30; i++) { String key = String.valueOf(i); new Thread(() -> { //向集合添加内容 map.put(key, UUID.randomUUID().toString().substring(0, 8)); //从集合中获取内容 System.out.println(map); }, "").start(); } }
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442)
at java.util.HashMap$EntryIterator.next(HashMap.java:1476)
at java.util.HashMap$EntryIterator.next(HashMap.java:1474)
at java.util.AbstractMap.toString(AbstractMap.java:554)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at com.guigu.map.ThreadDemo01.lambda$main$0(ThreadDemo01.java:21)
at java.lang.Thread.run(Thread.java:748)
解决办法:用ConcurrentHashMap取代HashMap
public class ThreadDemo02 { public static void main(String[] args) { //演示HashMap Map<String, String> map = new ConcurrentHashMap<>(); for (int i = 0; i < 20; i++) { String key = String.valueOf(i); new Thread(() -> { //向集合添加内容 map.put(key, UUID.randomUUID().toString().substring(0, 8)); //从集合中获取内容 System.out.println(map); }, "").start(); } } }