学无先后,达者为师

网站首页 编程语言 正文

详解HashMap并发修改异常

作者:wu1308156206 更新时间: 2022-07-10 编程语言

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

原文链接:https://blog.csdn.net/wu1308156206/article/details/125688755

栏目分类
最近更新