当前位置:   article > 正文

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

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());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

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

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/670946
推荐阅读
相关标签
  

闽ICP备14008679号