多线程下的Map操作

1.不安全的操作,容易报ConcurrentModificationException

  

 Map<String, String> map = new HashMap<>();
        for (int i = 0;i<10;i++){
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,5));
                System.out.println(map);
            }).start();
        }

 

2.修改为安全的操作

1.使用Collections 工具

Map<String, String> map = Collections.synchronizedMap(new HashMap<>());

2.使用JUC下面的

Map<String, String> map = new ConcurrentHashMap<>();

  为什么是安全的呢?---> 

ConcurrentHashMap.put()--->putVal()中采用synchronized


posted @ 2021-11-16 23:29  阿·超  阅读(695)  评论(0)    收藏  举报