本文作者:王一飞,叩丁狼高级讲师。原创文章,转载请注明出处。
#####概念
LinkedBlockingQueue按照api解释:一个基于链表而实现的有界阻塞队列。遵循先进先出原则,由队头入列,再从队尾出列。具体操作上跟ArrayBlockingQueue类似,区别在于底层维护数据上,LinkedBlockingQueue底层是一个链接,而ArrayBlockingQueue是一个数组。
内部结构
public class LinkedBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
private final AtomicInteger count = new AtomicInteger(); //队列元素个数
private final int capacity; //队列容器
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();
//队列数据节点
static class Node<E> {
E item;
Node<E> next;
Node(E x) {
item = x; }
}
}
######基本操作
public class App {
public static void main(String[] args) throws InterruptedException {
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue(5);
//入列
queue.add("a"); //队列满后抛异常
queue.put("b");//队列满后阻塞
queue.offer("c"); //入列失败返回false
System.out.println(queue);
queue.put("a");
queue.put("b");
queue.