接着上一篇,本篇直接上代码:
//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<>();