1、LinkedBlockingQueue属于Queue分支下的一个子类,与ArrayBlockingQueue不同,它底层采用链表的方式来存放数据,不过也可以给它设置容量,若不设置容量,默认是int的最大值,正常来说元素个数是达不到这个值的,可能先出现oom
2、由于底层采用的是单链表,只能从尾部添加,从头部获取
3、它是一个阻塞队列,采用了两把锁,实现了读写分离,什么意思呢,因为它是单向队列,只能从尾部加,头部取,所以加和取,可以互不干扰,如果用同一把锁,反而降低了效率,各用一把锁,读写操作可以并行执行
1、重要属性
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();
2、构造器
/**
* 无参构造,默认容量Integer.MAX_VALUE
*/
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
/**
* 有参构造,容量为capacity
*/
public LinkedBlockingQueue(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
// 初始化链表头尾,也就是先初始化一个哨兵节点,目的是在后续的方法中可以避免一些为空判断
last = head = new Node<E>(null);
}
/**
* 有参构造 此方法可传入一个集合
* c 需要加入队列的集合
*/
public LinkedBlockingQueue(Collection<? extends E> c) {
this(Integer.MAX_VALUE);
// 加锁
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
// 循环将元素入队
int n = 0;
for (E e : c) {
if (e == null)
throw new NullPointerException();
if (n == capacity)
throw new IllegalStateException("Queue full");
enqueue(new Node<E>(e));
++n;
}
count.set(n);
} finally {
putLock.unlock();
}
}
private void enqueue(Node<E> node) {
// 在尾部添加元素
last = last.next = node;
}
3、主要方法
3.1、offer(E e)
此方法往队列添加元素,成功返回true,失败返回false,不等待(不挂起线程)
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
// 获取元素个数
final AtomicInteger count = this.count;
// 队列已满 返回false
if (count.get() == capacity)
return false;
int c = -1;
// 初始化node
Node<E> node = new Node<E>(e);
// 加锁
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
// 判断容量
if (count.get() < capacity) {
// 入队
enqueue(node);
// 获取当前队列的元素个数,第一次进来,count肯定是0
c = count.getAndIncrement();
// 用当前元素个数+1,如果还小于队列容量,则将写队列中的线程唤醒
if (c + 1 < capacity)
notFull.signal();
}
} finally {
// 释放锁
putLock.unlock();
}
// 如果c==0,代表在添加元素之前,队列元素个数是0
// 如果有消费者在队列没有数据时进行消费,此时会挂起线程,限制有数据了,则将消费者队列中挂起的线程唤醒
if (c == 0)
signalNotEmpty();
return c >= 0;
}
private void enqueue(Node<E> node) {
// 在尾部添加元素
last = last.next = node;
}
3.2、offer(E e, long timeout, TimeUnit unit)
此方法往队列添加元素,当没有拿到锁,或者条件不满足时,先等待一段时间(timeout)
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
if (e == null) throw new NullPointerException();
// 将时间转换为纳秒
long nanos = unit.toNanos(timeout);
int c = -1;
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
// 加锁
putLock.lockInterruptibly();
try {
// 判断队列是否满了,如果满了,那么线程则进入notFull排队等待,
// 那么这里有个问题,为什么要用while,用if进行判断行不行,答案是不行,
// 会产生虚假唤醒的问题,比如,此时C(读线程),A(写线程),B(写线程),在队列中排队,C线程完成工作后,队列
// 有了空间,他就将notFull中等待的写线程进行唤醒,假设唤醒的是A线程,此时A线程并不是直接获得锁,而是从等待
// 队列进入了AQS队列,有了抢锁的资格,但是此时E(写线程)获得锁进来了,发现有空间,将数据放进去了,当E线程
// 是否锁资源后A线程获得了锁,如果不进行长度判断,直接进行写,则会将未被消费的数据覆盖
while (count.get() == capacity) {
// 时间不够则直接返回false 时间还够,则等待
if (nanos <= 0)
return false;
// 返回剩余的时间
nanos = notFull.awaitNanos(nanos);
}
// 入队
enqueue(new Node<E>(e));
c = count.getAndIncrement();
// 当前元素添加完后还有空间,则唤醒等待的写线程
if (c + 1 < capacity)
notFull.signal();
} finally {
// 释放锁
putLock.unlock();
}
// 添加成功 唤醒等待的读线程
if (c == 0)
signalNotEmpty();
return true;
}
private void enqueue(Node<E> node) {
// 在尾部添加元素
last = last.next = node;
}
3.3、put(E e) throws InterruptedException
此方法往队列中添加元素,不同的是,如果添加不成功,它会一直死等,直到添加成功为止
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
// 加锁
putLock.lockInterruptibly();
try {
// 判断容量,此处的while与offer里面的判断一样,空间不够则挂起当前线程
while (count.get() == capacity) {
notFull.await();
}
// 入队
enqueue(node);
c = count.getAndIncrement();
// 当前元素添加完后还有空间,则唤醒等待的写线程
if (c + 1 < capacity)
notFull.signal();
} finally {
// 释放锁
putLock.unlock();
}
// 添加成功 唤醒等待的读线程
if (c == 0)
signalNotEmpty();
}
private void enqueue(Node<E> node) {
// 在尾部添加元素
last = last.next = node;
}
3.4、poll()
此方法从队列头获取元素(出队),成功返回队列头的元素,失败返回null
public E poll() {
final AtomicInteger count = this.count;
// 判断队列是否有元素
if (count.get() == 0)
return null;
E x = null;
int c = -1;
// 加锁
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
// 判断队列是否有元素
if (count.get() > 0) {
// 元素出队
x = dequeue();
// 去除元素个数赋值给C,再减1
c = count.getAndDecrement();
// 此时如果队列还有元素,唤醒等待的读线程
if (c > 1)
notEmpty.signal();
}
} finally {
// 释放锁
takeLock.unlock();
}
// 如果原来的元素个数是等于限制容量,但是现在我消费了一个,
// 那么就有空间了,就可以往里面添加元素了,则可以唤醒等待中的写线程了
if (c == capacity)
signalNotFull();
return x;
}
private E dequeue() {
// 取出头节点(哨兵节点)
Node<E> h = head;
// 取出真正的第一个节点(第一个元素)
Node<E> first = h.next;
// 将哨兵节点的next指向自己,方便回收
h.next = h; // help GC
// 将first作为新的head
head = first;
// 拿到需要返回的值
E x = first.item;
// 将first的值置为空
first.item = null;
return x;
}
3.5、poll(long timeout, TimeUnit unit)
此方法从队列头获取元素(出队),成功返回队列头的元素,失败返回null,不同的是,如果队列为空,它会等待一段时间
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
E x = null;
int c = -1;
long nanos = unit.toNanos(timeout);
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
// 加锁
takeLock.lockInterruptibly();
try {
// 判断容量 如果队列没有元素,且时间足够,则挂起,否则就返回null
// 使用while避免虚假唤醒
while (count.get() == 0) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
// 出队
x = dequeue();
// 元素个数减减
c = count.getAndDecrement();
// 如果队列还有元素,则唤醒等待中的读线程
if (c > 1)
notEmpty.signal();
} finally {
// 释放锁
takeLock.unlock();
}
// 如果原来的元素个数是等于限制容量,但是现在我消费了一个,
// 那么就有空间了,就可以往里面添加元素了,则可以唤醒等待中的写线程了
if (c == capacity)
signalNotFull();
return x;
}
private E dequeue() {
// 取出头节点(哨兵节点)
Node<E> h = head;
// 取出真正的第一个节点(第一个元素)
Node<E> first = h.next;
// 将哨兵节点的next指向自己,方便回收
h.next = h; // help GC
// 将first作为新的head
head = first;
// 拿到需要返回的值
E x = first.item;
// 将first的值置为空
first.item = null;
return x;
}
3.6、take()
此方法从队列头获取元素(出队),成功返回队列头的元素,不同的是,如果队列为空,它会一直等待,等待别人唤醒,或者被打断后抛出异常
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
// 加锁
takeLock.lockInterruptibly();
try {
// 判断容量 如果队列没有元素,则挂起
// 使用while避免虚假唤醒
while (count.get() == 0) {
notEmpty.await();
}
// 出队
x = dequeue();
// 元素个数减减
c = count.getAndDecrement();
// 如果队列还有元素,则唤醒等待中的读线程
if (c > 1)
notEmpty.signal();
} finally {
// 释放锁
takeLock.unlock();
}
// 如果原来的元素个数是等于限制容量,但是现在我消费了一个,
// 那么就有空间了,就可以往里面添加元素了,则可以唤醒等待中的写线程了
if (c == capacity)
signalNotFull();
return x;
}
private E dequeue() {
// 取出头节点(哨兵节点)
Node<E> h = head;
// 取出真正的第一个节点(第一个元素)
Node<E> first = h.next;
// 将哨兵节点的next指向自己,方便回收
h.next = h; // help GC
// 将first作为新的head
head = first;
// 拿到需要返回的值
E x = first.item;
// 将first的值置为空
first.item = null;
return x;
}
3.7、peek()
查看队列的第一个元素
public E peek() {
if (count.get() == 0)
return null;
// 加锁
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
// 获取第一个元素
Node<E> first = head.next;
if (first == null)
return null;
else
return first.item;
} finally {
// 释放锁
takeLock.unlock();
}
}
3.8、remove(Object o)
移除队列中的元素
public boolean remove(Object o) {
if (o == null) return false;
// 加锁 读锁和写锁 为什么要加两把锁,
// 1、因为读写操作的是队列头部和尾部,但是删除的时候你并不知道你要删除的元素在哪个位置,
// 需要循环队列,加入要删除的队列正好是队头或者队尾,当前线程要对队尾元素进行删除,而另一个线程要在尾部添加元素,就乱了
fullyLock();
try {
// 循环队列
for (Node<E> trail = head, p = trail.next;
p != null;
trail = p, p = p.next) {
// 找到元素
if (o.equals(p.item)) {
// 进行移除
unlink(p, trail);
return true;
}
}
return false;
} finally {
// 释放锁
fullyUnlock();
}
}
void unlink(Node<E> p, Node<E> trail) {
// p是要删除的节点
p.item = null;
// trail是p的上一个节点,将上一个节点的next指向p的next,也就是跳过p
trail.next = p.next;
// 如果p是最后一个节点,那么last指向trail
if (last == p)
last = trail;
// 如果删除前容量是满的,那么删除了一个元素之后,就可以再往里面添加元素了
if (count.getAndDecrement() == capacity)
// 唤醒等待中的写线程
notFull.signal();
}
void fullyLock() {
putLock.lock();
takeLock.lock();
}
void fullyUnlock() {
takeLock.unlock();
putLock.unlock();
}
3.9、peek()
查看队列中第一个元素
public E peek() {
if (count.get() == 0)
return null;
// 加锁
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
// 获取第一个元素
Node<E> first = head.next;
// 为空返回空
if (first == null)
return null;
else
// 返回元素
return first.item;
} finally {
// 释放锁
takeLock.unlock();
}
}