Java里常用的集合哪些是线程安全的和不安全的

最近在做一个业务的时候,需要考虑线程的安全性,然后选用集合的时候专门去整理了一下。
线程安全的是:
Hashtable,ConcurrentHashMap,Vector ,CopyOnWriteArrayList ,CopyOnWriteArraySet
线程不安全的是:
HashMap,ArrayList,LinkedList,HashSet,TreeSet,TreeMap
最常用的Hashmap和HashTable我做了一下测试,就很明白能看出来,线程不安全时发生的问题了
先测HashMap的:

        Map<String,Integer> map = new HashMap<>();
		System.out.println("map的size---->" + map.size());
		Hashtable<String, Integer> table = new Hashtable<>();
		System.out.println("table的size---->" + table.size());
		
		Thread thread1 = new Thread(()->{
			for(int i = 0;i < 50000;i++){
				map.put(i + "", i);
			}
		});
		Thread thread2 = new Thread(()->{
			for(int i = 0;i < 50000;i++){
				map.put(i + "a", i);
			}
		});
		thread1.start();
		thread2.start();
		thread1.join();
		thread2.join();
		System.out.println("map的size---->" + map.size());
		System.out.println("table的size---->" + table.size());

看下结果:
在这里插入图片描述
同样的,再看下HashTable的运行结果:
在这里插入图片描述
这安全与不安全,还是比较明显的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值