LinkedBlockingQueue队列操作方法:
抛出异常 | 不抛异常 | 阻塞 | |
入队 | add | offer offer timeout | put |
出队 | revome | poll poll timeout | take |
查看 | element | peek |
以上操作都会调用入队(enqueue)、出队(dequeue)方法。其中队列的头(head.item)和尾(last.next)值为空null。
private void enqueue(Node<E> node) {
// assert putLock.isHeldByCurrentThread();
// assert last.next == null;
last = last.next = node;
}
private E dequeue() {
// assert takeLock.isHeldByCurrentThread();
// assert head.item == null;
Node<E> h = head;
Node<E> first = h.next;
h.next = h; // help GC
head = first;
E x = first.item;
first.item = null;
return x;
}
put方法阻塞是靠putLock的condition,当队列满时进入阻塞状态。
private final Condition notFull = putLock.newCondition();
while (count.get() == capacity) {
notFull.await();
}
take方法阻塞是靠takeLock的condition,当队列空时进入阻塞状态。
private final Condition notEmpty = takeLock.newCondition();
while (count.get() == 0) {
notEmpty.await();
}
其中,count是队列当前容量,是原子的。
private final AtomicInteger count = new AtomicInteger();