ArrayBlockingQueue是一個基於數組和鎖的有容量限制的阻塞隊列,事實上它的阻塞能力來自於鎖和條件隊列。
我們對關鍵代碼展開:
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的特點是容量限制,並且鎖範圍較大,所以大多數情況下可能不是好的選擇。