七、HashMap并发修改异常

  • Post author:
  • Post category:其他


HashMap是线程不安全的

public class HashMapTest {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();

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

上面代码也会出现并发修改异常

在这里插入图片描述

解决方法:

  1. 使用Collections

    Map<String,String> map = Collections.synchronizedMap(new HashMap<>());
    
  2. 使用ConcurrentHashMap

    Map<String,String> map = new ConcurrentHashMap<>();
    
  3. 使用HashTable



版权声明:本文为wu1308156206原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。