- 阻塞队列相对于非阻塞队列的好处:
在生产者-消费者模型中,它会对当前线程产生阻塞,如果一个线程从一个空的阻塞队列中取元素,此时线程会被阻塞直到阻塞队列中有了元素。当队列中有元素后,被阻塞的线程会自动被唤醒(不需要我们编写代码去唤醒)。这样提供了极大的方便性。而非阻塞队列则需要我们实现额外的同步策略,调用wait()和notify()方法。
- 常见的阻塞队列:
1.ArrayBlockingQueue
2.LinkedBlockingQueue
3.PriorityBlockingQueue
4.DelayQueue
5.SynchronousQueue
- 阻塞队列中的方法:
1.put(E e)
put方法用来向队尾存入元素,如果队列满,则等待
2.take()
take方法用来从队首取元素,如果队列为空,则等待
3.offer(E e,long timeout, TimeUnit unit)
offer方法用来向队尾存入元素,如果队列满,则等待一定的时间,当时间期限达到时,如果还没有插入成功,则返回false,否则返回true
4.poll(long timeout, TimeUnit unit)
poll方法用来从队首取元素,如果队列空,则等待一定的时间,当时间期限达到时,如果取到,则返回null,否则返回取得的元素
注:阻塞队列中还包括非阻塞队列中的方法,它们都进行了同步措施
- ArrayBlockQueue源码分析
1.成员变量:
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
private static final long serialVersionUID = -817911632652898426L;
private final E[] items;
private int takeIndex;
private int putIndex;
private int count;
private final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
}
可以看出它的底层实现是数组,takeIndex和putIndex分别表示队首元素和队尾元素的下标,count表示队列中元素的个数。lock是一个可重入锁,notEmpty和notFull是等待条件
2.构造函数:
public ArrayBlockingQueue(int capacity) {}
public ArrayBlockingQueue(int capacity, boolean fair) {}
public ArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair)
})
三个构造函数,第一个构造函数指定阻塞队列的大小,第二个构造函数指定阻塞队列的大小以及公平性,默认为false,即等待最久的元素不一定最先被取出,第三个构造函数还指定了初始化的容器
3.put方法:
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
final E[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == items.length)
notFull.await();
} catch (InterruptedException ie) {
notFull.signal(); // propagate to non-interrupted thread
throw ie;
}
insert(e);
} finally {
lock.unlock();
}
}
从put方法的实现可以看出,它先获取了锁,并且获取的是可中断锁,然后判断当前元素个数是否等于数组的长度,如果相等(队列为满),则调用notFull.await()进行等待,如果捕获到中断异常,则唤醒线程并抛出异常,当被其他线程唤醒时,通过insert(e)方法插入元素,最后释放锁
insert方法:
private void insert(E x) {
items[putIndex] = x;
putIndex = inc(putIndex);
++count;
notEmpty.signal();
}
添加元素以后将计数加1并唤醒消费者线程
4.take方法:
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == 0)
notEmpty.await();
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
throw ie;
}
E x = extract();
return x;
} finally {
lock.unlock();
}
}
判断当前元素个数是否等于0,如果等于0(队列为空),则调用notEmpty.await()进行等待,如果捕获到中断异常,则唤醒线程并抛出异常,当被其他线程唤醒时,通过extract()方法获得元素,最后释放锁
extract方法:
private E extract() {
final E[] items = this.items;
E x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}
计数减1并唤醒生产者线程,返回获得的元素
- 小结:
查看源码可知,阻塞队列不需要实现额外的同步策略以及线程间唤醒策略是因为take和put方法内部为我们实现了同步策略。首先take和put方法都将竞争ReentLock,所以同时只能有一个方法在执行。在put方法里判断是否队列为满,队列为满,则等待,直到被另外的线程(消费者线程唤醒),然后继续添加元素。而take判断是否为空,为空则等待,直到被唤醒在获得元素。