阻塞队列

LinkedBlockingQueue
- 内部使用Node 节点组成一个单链表
- head 、 last 并且保存了头尾节点、
- takeLock = new ReentrantLock();
- 删除的时候锁
- putLock = new ReentrantLock();
- 存放的时候锁
- notEmpty = takeLock.newCondition();
- 不为空时候的newCondition
- notFull = putLock.newCondition();
- 不满时候的newCondition
- capacity 容量
public class LinkedBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
static class Node<E> {
E item;
Node<E> next;
Node(E x) {
item = x; }
}
private final int capacity;
private final AtomicInteger count = new AtomicInteger();
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();
}
构造函数
默认的无参调用有参,并且使用 Integer的最大值。
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
直接把 容量设置为 Integer的最大值。并且初始化 队列, 设置头尾节点。
public LinkedBlockingQueue(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node<E>(null);
}
初始化之后的结构如下

类中的方法
- 可以看到类中的方法和 ArrayBlockingQueue 中类似
- 都是一些入队出队的方法
- 毕竟上层接口也是 Queue
- 都是一些入队出队的方法

添加元素
add 方法
- 在这里面会调用 offer 方法来做出实现
- 因为它们(LinkedBlockingQueue、ArrayBlockingQueue )是 AbstractQueue 的子类 所以在一些方法的调用流程上都是差不多的,走父类的方法,然后在用自己的具体实现。
- offer 方法 为false的时候,会抛出异常。
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
LinkedBlockingQueue
offer方法的具体实现
-
判断要添加的元素是不是为空
-
然后取出当前队列的大小
- 如果大小已经等于容量(已经满了) 直接 false
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
final AtomicInteger count = this.count;
if (count.get() == capacity)
LinkedBlockingQueue详解

本文深入解析了Java并发包中的LinkedBlockingQueue数据结构,包括其内部实现机制如链表结构、锁分离策略、条件变量等,并介绍了核心方法如offer、put、poll、take等的工作原理。
最低0.47元/天 解锁文章
1070

被折叠的 条评论
为什么被折叠?



