ArrayList,HashSet,HashMap等集合不是線程安全的.在多線程環(huán)境中使用這些集合可能會出現(xiàn)數(shù)據(jù)不一致的情況,或者產(chǎn)生異常。
Vector集合,HashTable集合是線程安全,在這些集合中使用synchronized關鍵字把方法修飾為同步方法,只允許由一個線程調(diào)用其中一個方法, 所以又把Vector,HashTable集合稱為同步集合。
在Collections工具類中提供了一組synchronizedXXX()方法可以把不是線程安全的集合轉(zhuǎn)換為線程安全的集合,這也是同步集合。
package com.wkcto.syncColleciton;
import java.util.ArrayList;
import java.util.Vector;
/**
* 并發(fā)下的ArrayList集合
*/
public class Test01 {
//創(chuàng)建ArrayList集合
// private static ArrayList<Integer> arrayList = new ArrayList<>();
//創(chuàng)建Vector集合
private static Vector<Integer> arrayList = new Vector<>();
//定義線程類,在該線程中不斷的向ArrayList集合中添加元素
private static class AddDataThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
arrayList.add( i );
}
}
}
public static void main(String[] args) throws InterruptedException {
//啟動三個線程,向ArrayList集合中添加數(shù)據(jù)
AddDataThread t1 = new AddDataThread();
AddDataThread t2 = new AddDataThread();
AddDataThread t3 = new AddDataThread();
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println( arrayList.size() );
/*
當程序運行后,會產(chǎn)生異常Exception in thread "Thread-2" Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: Index 48 out of bounds for length 15
ArrayList底層是使用數(shù)組來存儲數(shù)據(jù)的,在向ArrayList集合中添加元素時,如果元素的數(shù)量超過底層數(shù)組的長度,數(shù)組需要擴容, 在擴容過程中,沒有對數(shù)組進行保護,在多線程環(huán)境中可能會出現(xiàn)一致性被破壞的情況,一個線程在擴容,另外一個線程在存儲數(shù)據(jù),訪問了不一致的內(nèi)部狀態(tài),導致了數(shù)組的越界
還有一個可能出現(xiàn)的問題,最終集合的容量可能不準確,這也是多線程訪問沖突造成的
解決方法:
在List集合中還有實現(xiàn)類是Vector,它的底層也是數(shù)組,它是線程安全的,把ArrayList換成Vector即可
Vector中的操作都使用了synchronized關鍵字把方法修飾為同步方法, 即在多線程環(huán)境 中,只能有某一個線程調(diào)用它的某個方法, 所以 也稱Vector集合為同步集合
*/
}
}
package com.wkcto.syncColleciton;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
/**
* HashMap不是線程安全的
*/
public class Test02 {
//創(chuàng)建HashMap集合,存儲<整數(shù),整數(shù)的二進制形式>
// private static Map<String,String> map = new HashMap<>();
//使用線程安全的HashTable存儲
private static Map<String,String> map = new Hashtable<>();
//定義線程類,向map中添加數(shù)據(jù)
private static class AddDataThread extends Thread{
private int start = 0 ;
public AddDataThread(int start) {
this.start = start;
}
@Override
public void run() {
//通過循環(huán)把奇數(shù)與偶數(shù)分開
for (int i = start; i < start+ 100000; i+=2) {
//把整數(shù),整數(shù)的二進制添加到map中
map.put(Integer.toString(i), Integer.toBinaryString(i));
}
}
}
public static void main(String[] args) throws InterruptedException {
//創(chuàng)建線程把從0開始的偶數(shù)及對應的二進制添加到map中
AddDataThread t1 = new AddDataThread(0);
//創(chuàng)建線程把從1開始的奇數(shù)及對應的二進制添加到map中
AddDataThread t2 = new AddDataThread(1);
t1.start();
t2.start();
t1.join();
t2.join();
//兩個線程添加完成后,查看map中鍵值對的數(shù)量
System.out.println(map.size());
/*
運行程序,輸出map的鍵值對數(shù)量,它可能是一個小于100000的數(shù)字,即出現(xiàn)了數(shù)據(jù)不一致的線程安全問題
解決方法:
可以把HashMap集合換成HashTable
在HashTable集合中,使用synchronized關鍵字把操作修飾為同步方法, 即多線程環(huán)境中只允許由一個線程來操作HashTable集合,它是線程安全的, 也把HashTable稱為同步集合
*/
}
}