阻塞隊列,阻塞隊列java
1、阻塞隊列的原理
阻塞隊列與普通隊列的區別在於:阻塞隊列為空白時,從隊列中擷取元素的操作將會被阻塞,當隊列為滿時,往隊列裡添加元素的操作會被阻塞。
試圖從空的阻塞隊列中擷取元素的線程將會被阻塞,直到其他的線程往空的隊列插入新的元素。同樣,試圖往已滿的阻塞隊列中添加新元素的線程同樣也會被阻塞,直到其他的線程使隊列重新變得空閑起來
2、阻塞隊列的簡單實現
/** * 基於鏈表實現的一個阻塞隊列 * * @author jade * */public class BlockingQueue { private int capacity ; // 阻塞隊列容量 private List queue = new LinkedList(); // 基於鏈表實現的一個阻塞隊列 public BlockingQueue() { this(Integer.MAX_VALUE); } public BlockingQueue(int capacity) { this.capacity = capacity; } /** * 入隊列 * * @param item * @throws InterruptedException */ public synchronized void enqueue(Object item) throws InterruptedException { while (this.queue.size() == this.capacity) { wait(); } if (this.queue.size() == 0) { notifyAll(); } this.queue.add(item); } /** * 出隊列 * * @return * @throws InterruptedException */ public synchronized Object dequeue() throws InterruptedException { while (this.queue.size() == 0) { wait(); } if (this.queue.size() == this.capacity) { notifyAll(); } return this.queue.remove(0); }}注意:
1)在enqueue和dequeue方法內部,只有隊列的大小等於上限(capacity)或者下限(0)時,才調用notifyAll方法,小於時不調用。
如果隊列的大小既不等於上限,也不等於下限,任何線程調用enqueue或者dequeue方法時,都不會阻塞,就不需要喚醒,都能夠正常的往隊列中添加或者移除元素。
2)enqueue和dequeue方法都加了synchronized ,在進入synchronized的時候擷取鎖,退出的時候釋放鎖。而如果沒有synchronized,直接使用wait/notify時,無法確認哪個鎖。
3、LinkedBlockingQueue
在java.util.concurrent包下提供了若干個阻塞隊列,其中LinkedBlockingQueue基於鏈表實現的一個阻塞隊列,在建立LinkedBlockingQueue對象時如果不指定容量大小,則預設大小為Integer.MAX_VALUE。
首先看一下LinkedBlockingQueue類中的幾個成員變數:
private static final long serialVersionUID = -6903933977591709194L; private final int capacity; private final AtomicInteger count = new AtomicInteger(); transient Node<E> head; private transient Node<E> last; private final ReentrantLock takeLock = new ReentrantLock(); private final Condition notEmpty = this.takeLock.newCondition(); private final ReentrantLock putLock = new ReentrantLock(); private final Condition notFull = this.putLock.newCondition();
可以看出,LinkedBlockingQueue中用來儲存元素的實際上是一個鏈表,head和last分別表示鏈表的前端節點和下一節點, capacity表示隊列的容量。
takelock,putLock 是可重新進入鎖,notEmpty和notFull是等待條件。
下面看一下LinkedBlockingQueue的構造器,構造器有三個重載版本:
public LinkedBlockingQueue() { this(Integer.MAX_VALUE); } public LinkedBlockingQueue(int paramInt) { if (paramInt <= 0) { throw new IllegalArgumentException(); } this.capacity = paramInt; this.last = (this.head = new Node(null)); } public LinkedBlockingQueue(Collection<? extends E> paramCollection) { this(Integer.MAX_VALUE); ReentrantLock localReentrantLock = this.putLock; localReentrantLock.lock(); try { int i = 0; Iterator localIterator = paramCollection.iterator(); while (localIterator.hasNext()) { Object localObject1 = localIterator.next(); if (localObject1 == null) { throw new NullPointerException(); } if (i == this.capacity) { throw new IllegalStateException("Queue full"); } enqueue(new Node(localObject1)); i++; } this.count.set(i); } finally { localReentrantLock.unlock(); } }
第一個構造器預設容量是Integer.MAX_VALUE,第二個構造器只有一個參數用來指定容量,第三個構造器可以指定一個集合進行初始化。
然後看它的兩個關鍵方法的實現:put()和take():
public void put(E paramE) throws InterruptedException {
// 確保放入的元素是非空的 if (paramE == null) { throw new NullPointerException(); } int i = -1; Node localNode = new Node(paramE); ReentrantLock localReentrantLock = this.putLock; AtomicInteger localAtomicInteger = this.count;
// 響應中斷 localReentrantLock.lockInterruptibly(); try {
while (localAtomicInteger.get() == this.capacity) { this.notFull.await(); // 阻塞 } enqueue(localNode); i = localAtomicInteger.getAndIncrement(); if (i + 1 < this.capacity) { this.notFull.signal(); ///使用了signal()提高效能, put的時候對notFull 條件隊列中阻塞的線程進行喚醒。 } } finally { localReentrantLock.unlock(); } if (i == 0) { signalNotEmpty(); // put 的時候,會在i == 0 的情況下對 notEmpty 條件隊列中阻塞的線程進行喚醒,但是這個需要擷取takeLock鎖。
}
}
public E take() throws InterruptedException { int i = -1; AtomicInteger localAtomicInteger = this.count; ReentrantLock localReentrantLock = this.takeLock; localReentrantLock.lockInterruptibly(); Object localObject1; try { while (localAtomicInteger.get() == 0) { this.notEmpty.await(); } localObject1 = dequeue(); i = localAtomicInteger.getAndDecrement(); if (i > 1) { this.notEmpty.signal(); } } finally { localReentrantLock.unlock(); } if (i == this.capacity) { signalNotFull(); } return (E)localObject1; }
跟put方法實現很類似,只不過put方法等待的是notFull訊號,而take方法等待的是notEmpty訊號
LinkedBlockingQueue內部維持著一個資料緩衝隊列(該隊列由一個鏈表構成),當生產者往隊列中放入一個資料時,隊列會從生產者手中擷取資料,並緩衝在隊列內部,而生產者立即返回;只有當隊列緩衝區達到最大值緩衝容量時(LinkedBlockingQueue可以通過建構函式指定該值),才會阻塞生產者隊列,直到消費者從隊列中消費掉一份資料,生產者線程會被喚醒,反之對於消費者這端的處理也基於同樣的原理。
而LinkedBlockingQueue之所以能夠高效的處理並發資料,還因為其對於生產者端和消費者端分別採用了獨立的鎖來控制資料同步,這也意味著在高並發的情況下生產者和消費者可以並行地操作隊列中的資料,以此來提高整個隊列的並發效能。
LinkedBlockingQueue內部使用ReentrantLock實現插入鎖(putLock)和取出鎖(takeLock)。putLock上的條件變數是notFull,即可以用notFull喚醒阻塞在putLock上的線程。takeLock上的條件變數是notEmtpy,即可用notEmpty喚醒阻塞在takeLock上的線程。
參考了如下部落格:
http://www.cnblogs.com/moonandstar08/p/4893337.html
http://www.cnblogs.com/dolphin0520/p/3932906.html