1. 程式人生 > >多執行緒(九): HashTable、HashMap和ConcurrentHashMap

多執行緒(九): HashTable、HashMap和ConcurrentHashMap

public class HashTest {
    static Map<String, Integer> map = new HashMap<String, Integer>();
    // static Map<String, Integer> map = new Hashtable<>();
    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                int raddom = new
Random().nextInt(); String threadName = Thread.currentThread().getName(); map.put(threadName, raddom); System.out.println(Thread.currentThread().getName() + "\t" + map.get(threadName)); })
.start(); } } }

這裡寫圖片描述

HashMap

public class
HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
public V put(K key, V value); public V get(Object key); }
// 可以通過Collections將非線性安全轉為執行緒安全
Map<Object, Object> map = Collections.synchronizedMap(new HashMap<>());

Hashtable

public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable {
    // 執行緒安全 同步方法synchronized
    public synchronized V put(K key, V value);

    // 執行緒安全 同步方法synchronized
    public synchronized V get(Object key);
}    

上面示例使用Hashtable就會每次都能獲取到資料