版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vbirdbest/article/details/81749089
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就会每次都能获取到数据