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