首先我们来看一下它的代码结构
public class LinkedBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
//...
static class Node<E> {//队列中存储元素的结构
E item;
/**
* One of:
* - the real successor Node
* - this Node, meaning the successor is head.next
* - null, meaning there is no successor (this is the last node)
*/
Node<E> next;
Node(E x) { item = x; }
}
//队列可以放置元素个数的大小,可以指定,默认为Integer.MAX_VALUE
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();
//与从队列中拿元素的锁对应,用于线程之间通信(类似于synchronized、wait(),notify())
private final Condition notEmpty = takeLock.newCondition();
//从队列中添加元素的锁
private final ReentrantLock putLock = new ReentrantLock();
//与从队列中添加元素的锁对应,用于线程之间通信(类似于synchronized、wait(),notify())
private final Condition notFull = putLock.newCondition();
//...
}
LinkedBlockingQueue 是一个基于链表结构的 队列,下面是他的一些主要方法:
我们先来看看offer(e)方法:
public boolean offer(E e) {//e 为要加入此队列的元素
if (e == null) throw new NullPointerException();
final AtomicInteger count = this.count;//此队列中的元素个数
if (count.get() == capacity)//判断队列是否已满,假如已经满了,则返回false
return false;
int c = -1;
Node<E> node = new Node(e);//新建一个节点
final ReentrantLock putLock = this.putLock;
putLock.lock();//加锁操作(此锁为独占锁),这里是putLock(LinkedBlockingQueue里一共有两个锁,putLock和takeLock)
try {
if (count.get() < capacity) {
enqueue(node);
c = count.getAndIncrement();//此队列中的元素个数加 1
if (c + 1 < capacity)
notFull.signal();//condition 唤醒一个阻塞在锁外部的线程,告诉那个线程可以尝试添加到此队列的操作(类似于notify方法)
}
} finally {
putLock.unlock();//释放独占锁
}
if (c == 0)
signalNotEmpty();//队列中此时不为空,可以从队列中拿元素
return c >= 0;
}
private void enqueue(Node<E> node) {
// assert putLock.isHeldByCurrentThread();
// assert last.next == null;
last = last.next = node;//将此节点设置为此队列中的最后一个节点
}
private void signalNotEmpty() {
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();//加锁操作(此锁为独占锁),这里是putLock(LinkedBlockingQueue里一共有两个锁,putLock和takeLock)
try {
notEmpty.signal();//condition 唤醒一个阻塞在锁外部的线程,告诉那个线程可以尝试从此队列中拿出元素的操作(类似于notify方法)
} finally {
takeLock.unlock();//释放独占锁
}
}
困,先到这里了。。。。。。