验证 Java HashMap 是否线程安全。
创建两个 线程 往 Java HashMap 集合 中添加元素,验证 Java HashMap 是否线程安全。
MyRunnable 代码:
public class MyRunnable implements Runnable {
private int start;
private int end;
public static HashMap<Integer,Integer> map = new HashMap<>();
public MyRunnable() {
}
public MyRunnable(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i < end; i++) {
map.put(i,i);
}
System.out.println(Thread.currentThread().getName() + "添加完毕");
}
}
测试代码:
public class Test {
public static void main(String[] args) throws InterruptedException {
System.out.println("嗨客网(www.haicoder.net)\n");
MyRunnable r1 = new MyRunnable(1,1000);
Thread t1 = new Thread(r1,"线程A");
// 线程运行
t1.start();
for (int i = 1000; i <= 2000; i++) {
r1.map.put(i,i);
}
// 打印集合长度
System.out.println("集合长度:" + MyRunnable.map.size());
}
}
运行结果如下图:
以上案例发现最终的集合长度小于 2000 ,得出 HashMap 是线程不安全的,若要解决该问题,应该使用线程安全的 Hashtable 或者 ConcurrentHashMap。