LinkedBlockingQueue
LinkedBlockingQueue队列跟ArrayBlockingQueue一样都实现了BlockingQueue。因此同样是阻塞队列,有三种删除和三种添加的方法。LinkedBlockingQueue的底层是基于链表实现。ArrayBlockingQueue通过一个锁和锁的两个条件对象保证并发的安全性,LinkedBlockingQueue通过两个锁和每个锁的一个条件队列来控制并发的安全性。
基本属性如下:
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
private final int capacity;
private final AtomicInteger count = new AtomicInteger(0);
private transient Node<E> head;
private transient Node<E> last;
private final ReentrantLock takeLock = new ReentrantLock();
private final Condition notEmpty = takeLock.newCondition();
private final ReentrantLock putLock = new ReentrantLock();
private final Condition notFull = putLock.newCondition();
ArrayBlockingQueue只有一个锁,因此不支持添加和删除元素并行执行,LinkedBlockingQueue有一个取锁和放锁,因此支持并行的取和放。但是,取和取,放和放之间是互斥的。每次只能有一个线程拿到锁。
add方法实现
同理add方法是父类AbstractQueue队列实现,其中调用了offer方法。如果因为队列满了,添加失败抛出IllegalStateException异常。
offer实现
public boolean offer(E e) {
if (e == null) throw new NullPointerException();//插入元素为空抛出异常
final AtomicInteger count = this.count;
if (count.get() == capacity)//队列已满,返回false
return