集合不安全之 ---> 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使用的分段锁

猜你喜欢

转载自www.cnblogs.com/cb1186512739/p/12736536.html