接着上一篇,本篇直接上代码:
//Map<Object, Object> map = new HashMap<>();
//Map<Object, Object> map = Collections.synchronizedMap(new HashMap<>());
Map<Object, Object> map = new ConcurrentHashMap<>();
for(int i = 1;i <= 100; i++){
new Thread(()->{
map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
System.out.println(map);
},String.valueOf(i)).start();
}
在多线程情况下,使用
Map<Object, Object> map = new HashMap<>();
会产生 java.util.ConcurrentModificationException异常
解决方式:
-
Map<Object, Object> map = Collections.synchronizedMap(new HashMap<>());
-
Map<Object, Object> map = new ConcurrentHashMap<>();
本文探讨了在多线程环境下使用Map的并发问题,通过对比HashMap、synchronizedMap和ConcurrentHashMap,展示了如何避免ConcurrentModificationException异常,确保线程安全。
710

被折叠的 条评论
为什么被折叠?



