Java教程

多线程下的Map操作

本文主要是介绍多线程下的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

                    
这篇关于多线程下的Map操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!