1. 结构概述
- public class LinkedBlockingQueue extends AbstractQueue implements BlockingQueue, java.io.Serializable {
- private final int capacity; // 默认 Integer.MAX_VALUE
- private final AtomicInteger count = new AtomicInteger(); // 容量
- transient Node head; // 头结点 head.item == null
- private transient Node last; // 尾节点 last.next == null
- 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 item;
- Node next;
- Node(E x) { item = x; }
- }
- }
LinkedBlockingQueue 的结构如图所示:
如图所示,
LinkedBlockingQueue 其实就是一个简单的单向链表, 其中头部元素的数据为空, 尾部元素的 next 为空; 因为读写都有竞争, 所以在头部和尾部分别有一把锁; 同时还有对应的两个条件队列;
下面我们就读写操作, 对源码简单分析:
来源: https://www.2cto.com/kf/201904/802533.html