最近在做一个业务的时候,需要考虑线程的安全性,然后选用集合的时候专门去整理了一下。
 线程安全的是:
 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的运行结果:
 
 这安全与不安全,还是比较明显的



















