http://m.blog.csdn.net/blog/luoyuyou/38265817
java
ArrayBlockingQueue是一個基於數組和鎖的有容量限制的阻塞隊列,事實上它的阻塞能力來自於鎖和條件隊列。數組
咱們對關鍵代碼展開:this
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { checkNotNull(e); long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == items.length) { if (nanos <= 0) return false; nanos = notFull.awaitNanos(nanos); } enqueue(e); return true; } finally { lock.unlock(); } }這裏的過程比較簡單也比較熟悉,無非是先獲取鎖,查看當前個數和容量對比,以後會限時阻塞而後入隊列,發送信號而且返回true,最後釋放鎖。
public E poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == 0) { if (nanos <= 0) return null; nanos = notEmpty.awaitNanos(nanos); } return dequeue(); } finally { lock.unlock(); } }與offer的過程相似,區別只是會從隊列中取出節點。
ArrayBlockingQueue的特色是容量限制,而且鎖範圍較大,因此大多數狀況下可能不是好的選擇。
spa