1、通過synchronized 關(guān)鍵字給方法加上內(nèi)置鎖來實(shí)現(xiàn)線程安全
Timer,TimerTask,Vector,Stack,HashTable,StringBuffer。
2、原子類Atomicxxx—包裝類的線程安全類
如AtomicLong,AtomicInteger等等。
Atomicxxx 是通過Unsafe 類的native方法實(shí)現(xiàn)線程安全的。
3、BlockingQueue 和BlockingDeque
BlockingDeque接口繼承了BlockingQueue接口,BlockingQueue 接口的實(shí)現(xiàn)類有ArrayBlockingQueue ,LinkedBlockingQueue ,PriorityBlockingQueue 而BlockingDeque接口的實(shí)現(xiàn)類有LinkedBlockingDeque。
BlockingQueue和BlockingDeque 都是通過使用定義為final的ReentrantLock作為類屬性顯式加鎖實(shí)現(xiàn)同步的。
4、CopyOnWriteArrayList和 CopyOnWriteArraySet
CopyOnWriteArraySet的內(nèi)部實(shí)現(xiàn)是在其類內(nèi)部聲明一個(gè)final的CopyOnWriteArrayList屬性,并在調(diào)用其構(gòu)造函數(shù)時(shí)實(shí)例化該CopyOnWriteArrayList,CopyOnWriteArrayList采用的是顯式地加上ReentrantLock實(shí)現(xiàn)同步,而CopyOnWriteArrayList容器的線程安全性在于在每次修改時(shí)都會(huì)創(chuàng)建并重新發(fā)布一個(gè)新的容器副本,從而實(shí)現(xiàn)可變性。
5、Concurrentxxx
最常用的就是ConcurrentHashMap,當(dāng)然還有ConcurrentSkipListSet和ConcurrentSkipListMap等等。
ConcurrentHashMap使用了一種完全不同的加鎖策略來提供更高的并發(fā)性和伸縮性。ConcurrentHashMap并不是將每個(gè)方法都在同一個(gè)鎖上同步并使得每次只能有一個(gè)線程訪問容器,而是使用一種粒度更細(xì)的加鎖機(jī)制——分段鎖來實(shí)現(xiàn)更大程度的共享。
在這種機(jī)制中,任意數(shù)量的讀取線程可以并發(fā)訪問Map,執(zhí)行讀取操作的線程和執(zhí)行寫入操作的線程可以并發(fā)地訪問Map,并且一定數(shù)量的寫入線程可以并發(fā)地修改Map,這使得在并發(fā)環(huán)境下吞吐量更高,而在單線程環(huán)境中只損失非常小的性能。
6、ThreadPoolExecutor
ThreadPoolExecutor也是使用了ReentrantLock顯式加鎖同步。
7、Collections中的synchronizedCollection(Collection c)方法可將一個(gè)集合變?yōu)榫€程安全,其內(nèi)部通過synchronized關(guān)鍵字加鎖同步。