多线程下的Map操作


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

 Map 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 map = Collections.synchronizedMap(new HashMap<>());

2.使用JUC下面的

Map map = new ConcurrentHashMap<>();

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

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