1. 程式人生 > >多線程下並發數據結構

多線程下並發數據結構

繼續 table list接口 sync cto vector lock 安全性 tor

1、並發List
  在List下中有ArrayList 、LinkedList 、Vector 三種數據結構,其中Vector屬於線程安全的。
  在List下還有CopyOnWriteArrayList類實現的List接口,它也是線程安全的。

  CopyOnWriteArrayList與Vector進行對比:
    (1)鎖的位置
      CopyOnWriteArrayList的實現是在讀操作中去除鎖,而寫中有鎖並且多了復制操作。
      Vector在讀操作和寫操作中都添加了鎖。
    (2)速度比較
      CopyOnWriteArrayList因為在讀操作中去除了鎖,所以其速度比Vector快。但是CopyOnWriteArrayList中多了復制操作,所以其寫的速度要比Vect慢。

    個人推薦:在讀多寫少時用CopyOnWriteArrayList,如果讀少寫多時,用Vector

2、並發Set


  與List類似,Set也有一個CopyOnWriteArraySet,它實現了Set接口,線程安全。

  CopyOnWriteArraySet,其內部實現完全依賴於CopyOnWriteArrayList,所以CopyOnWriteArrayList所具有的特性,CopyOnWriteArraySet全具有。

  個人推薦:在讀多寫少時,用CopyOnWriteArraySet。
3、並發Map
  Map下有HashMap、HashTable(子類LinkedHashMap)、TreeMap、ConcurrentHashMap。其中線程安全的是HashTable和ConcurrentHashMap。
  ConcurrentHashMap與HashTable進行對比:
    ConcurrentHashMap 的get()中不加鎖,put()中又使用減少鎖粒度的方式來進行同步的,而不是想HashTable使用synchronized簡單的進行同步,所以其效率比HashTable高.
  鎖粒度:

  拿ConcurrentHashMap來說,他不是將整個HashMap進行加鎖,而是將HashMap分成很多段,需要put()操作時,根據其hashcode獲取
  該段,對該段進行加特定的鎖,其他段可以被其他線程繼續使用加鎖。

  個人推薦:如果不考慮安全性,使用HashMap。考慮安全性使用ConcurrentHashMap。
4、並發Queue
  並發隊列有兩類,一類支持高並發的ConcurrentLinkedQueue,另一類是阻塞隊列BlockingQueue。

  詳解:
    ConcurrentLinkedQueue采用的是無鎖的方式,所以其性能在高並發中很好。
    BlockingQueue采用的是生產者消費者模式的方式進行加鎖。Blocking的具體實現有ArrayBlockingQueue和LinkedBlockingQueue

  個人推薦:如果需要高並發下有高性能,使用ConcurrentLinkedQueue。如果想要實現數據在多線程中共享,使用BlockingQueue。

5、並發Dueue(雙端隊列)
Dueue的具體實現有LinkedBlockingDueue。Dueue與Queue相比,Dueue繼承了Queue,所以它的功能更多。但是LinkedBlockingDueue的性能遠遠低於LinkedBlockingQueue,更低於ConcurrenLinkedQueue。

多線程下並發數據結構