日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

詳解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

欄目分類
最近更新