? ? 前面介紹了5種并發(fā)隊列的原理,ConcurrentLinkedQueue、LinkedBlockingQueue、ArrayBlockingQueue、PriorityBlockingQueue和DelayQueue。下面橫向的對比一下這5中并發(fā)隊列的異同。
? ??ConcurrentLinkedQueue是非阻塞無界的雙向FIFO隊列,ConcurrentLinkedQueue是5個中唯一非阻塞的。內(nèi)部使用CAS算法+自旋的方式進(jìn)行元素的入隊和出隊。主要成員變量:
private transient volatile Node?head; //內(nèi)部雙向列表的頭節(jié)點,volatile保證內(nèi)存可見性。
private transient volatile Node?tail;?//內(nèi)部雙向列表的尾節(jié)點,volatile保證內(nèi)存可見性。
private static final sun.misc.Unsafe UNSAFE;//UNSAFE實例用來執(zhí)行CAS算法
? ??LinkedBlockingQueue是阻塞有界的單鏈表隊列。內(nèi)部有兩個ReentrantLock對象,分別控制元素的入隊和出隊的原子性,同時還有兩個條件變量來實現(xiàn)生產(chǎn)-消費模式。主要成員變量:
transient Node<E> head;
private transient Node<E> last;
private final AtomicInteger count = new AtomicInteger();
private final ReentrantLock takeLock = new ReentrantLock();
private final ReentrantLock putLock = new ReentrantLock();
private final Condition notEmpty = takeLock.newCondition();
private final Condition notFull = putLock.newCondition();
? ??ArrayBlockingQueue是阻塞有界的數(shù)組隊列。內(nèi)部初始化一個固定大小的數(shù)組存儲元素,一個ReentrantLock對象控制元素的入隊和出隊,有兩個條件變量用來實現(xiàn)生產(chǎn)-消費模式。主要成員變量:
final Object[]items;
final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
? ??PriorityBlockingQueue是阻塞無界帶有優(yōu)先級的隊列。內(nèi)部使用平衡二叉樹堆實現(xiàn)優(yōu)先級,一個ReentrantLocklock對象控制元素的入隊和出隊,通過CAS操作allocationSpinLock變量來控制只能有一個線程對隊列進(jìn)行擴(kuò)容,只有一個條件變量用來實現(xiàn)消費模式。主要成員變量:
private transient Object[]queue;
private transient volatile int allocationSpinLock;
private final ReentrantLock lock;
private final Condition notEmpty;
? ??DelayQueue是阻塞無界的延遲隊列。內(nèi)部有個PriorityQueue優(yōu)先隊列存在元素,用元素的過期時間進(jìn)行比較優(yōu)先級。內(nèi)部實現(xiàn)了leader-follower模式,使用ReentrantLock和條件變量來實現(xiàn)元素的指定過期時間等待。主要成員變量:
private final transient ReentrantLock lock = new ReentrantLock();
private final PriorityQueue<E> q = new PriorityQueue<E>();
private Thread leader = null;
private final Condition available = lock.newCondition();
????今天的分享就到這,有看不明白的地方一定是我寫的不夠清楚,所有歡迎提任何問題以及改善方法。