LinkedBlockingDeque自動阻塞的雙端隊列。
增刪元素的方法都是用ReentrantLock上鎖的。
add方法無返回值,滿了報異常,offer方法滿了return false,put方法滿了await自動阻塞。
以putFirst(E e)爲例:
final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
public void putFirst(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
while (!linkFirst(node))//returns false if full.
notFull.await(); //實現list滿了的情況下就會自動阻塞
} finally {
lock.unlock();
}
}
以pollFirst()爲例,peek,get等方法均不阻塞
public E pollFirst() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return unlinkFirst();
} finally {
lock.unlock();
}
}
只有take方法是自動阻塞的,調用condition的await方法進行阻塞
public E takeFirst() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
E x;
while ( (x = unlinkFirst()) == null)
notEmpty.await();
return x;
} finally {
lock.unlock();
}
}