Java容器HashMap线程不安全、Hashtable和ConcurrentHashMap线程安全的案例

一句话,集合HashMap线程不安全、集合Hashtable和ConcurrentHashMap线程安全,以下是实验证明。

注意:假如电脑不是很给力,请先保存好自己的文档之后再做实验,因为一下代码启动了两个线程,可能会使得CPU的占用率达到100%,导致电脑死机,当然程序员的电脑都是铁打的,假如是这样就放心的跑吧,反正是月末,过几天又要发工资了,如果死机了,记得下个月买台电脑,假如没有死机,你就把for的参数搞大一点,直到死机,给自己找个理由换电脑。

package com.yarm.test;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;

public class HashMapThread {

	//实例化
	static HashMap<Integer, Integer> hashMap = new HashMap<>();
	static Hashtable<Integer, Integer> hashTable = new Hashtable<>();
	static ConcurrentHashMap<Integer, Integer> concurrentHashMap = new ConcurrentHashMap<>();
	
	//内部类,该类实现了Runnable接口
	public static class MulThreadHashMapTest implements Runnable{

		@Override
		public void run() {
			for (int i = 0; i < 1000000; i++) {
				hashMap.put(i, i);
				hashTable.put(i, i);
				concurrentHashMap.put(i, i);
			}
		}
		
	}
	
	// main 函数
	public static void main(String[] args) throws InterruptedException {
		//启动两个线程来测试
		Thread t1 = new Thread(new MulThreadHashMapTest());
		Thread t2 = new Thread(new MulThreadHashMapTest());
		
		t1.start();
		t2.start();
		t2.join();t1.join();
		
		System.out.println("HashMap线程结束之后的长度:" + hashMap.size());
		System.out.println("hashTable线程结束之后的长度:" + hashTable.size());
		System.out.println("concurrentHashMap线程结束之后的长度:" + concurrentHashMap.size());
	}
}

控制台输出:

HashMap线程结束之后的长度:1069901
hashTable线程结束之后的长度:1000000
concurrentHashMap线程结束之后的长度:1000000

实验结果:

由实验结果,HashMap输出的长度1069901,不等于1000000,说明在多线程的情况之下,HashMap线程不安全;HashTable和concurrentHashMap多线程结束之后长度等于1000000,说明线程安全。

注意:

HashMap输出的长度可能有以下三种情况:

1.程序正常结束,HashMap刚好等于预期值;

2.程序正常结束,但小于预期的值,比如上边的实验结果;

3.程序一直没有结束,可能死锁了。

猜你喜欢

转载自blog.csdn.net/HelloWorldYangSong/article/details/81148442