集合不安全之 ---> Map

不废话,直接上代码

   //演示HashMap类的并发问题
    @Test
    public void demo1() {
        Map<String, Integer> map = new HashMap<>();
        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), random.nextInt());
                System.out.println(map);
            }).start();
        }

        //报错:Exception in thread "Thread-0" Exception in thread "Thread-1" java.util.ConcurrentModificationException
    }

解决方法:
使用ConcurrentHashMap类
使用Collections.synchronizedMap()方法
ConcurrentHashMap使用的分段锁
posted @ 2020-04-20 11:05  IT路上的小白  阅读(147)  评论(0编辑  收藏  举报