首页 > 其他分享 >HashMap、Hashtable、ConcurrentHashMap线程安全问题

HashMap、Hashtable、ConcurrentHashMap线程安全问题

时间:2023-03-14 20:33:15浏览次数:39  
标签:ConcurrentHashMap HashMap Thread 线程 Hashtable new

public class HashMapDemo {

    public static void main(String[] args) throws InterruptedException {
        // HashMap是线程不安全的
        // Hashtable是线程安全的,采用悲观锁synchronized的形式保证数据安全性
        // 只要有线程访问,会将整张hash表锁住,所以效率太低
        // ConcurrentHashMap是线程安全的,并且效率相对高效
        HashMap<String, String> hashMap = new HashMap<>();
        Hashtable<String, String> hashtable = new Hashtable<>();
        ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<>();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 25; i++) {
                concurrentHashMap.put(i + "", i + "");
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 25; i < 51; i++) {
                concurrentHashMap.put(i + "", i + "");
            }
        });

        t1.start();
        t2.start();

        Thread.sleep(1000);

        for (int i = 1; i < 51; i++) {
            System.out.println(concurrentHashMap.get(i + ""));
        }
    }
}

 

标签:ConcurrentHashMap,HashMap,Thread,线程,Hashtable,new
From: https://www.cnblogs.com/weiduaini/p/17216248.html

相关文章