本文参考资料:https://blog.youkuaiyun.com/javazejian/article/details/77410889
一. 拥塞队列概要
阻塞队列与我们平常接触的普通队列(LinkedList或ArrayList等)的最大不同点,在于阻塞队列支持阻塞添加和阻塞删除方法
- 阻塞添加
所谓的阻塞添加是指当阻塞队列元素已满时,队列会阻塞加入元素的线程,直队列元素不满时才重新唤醒线程执行元素加入操作。 - 阻塞删除
阻塞删除是指在队列元素为空时,删除队列元素的线程将被阻塞,直到队列不为空再执行删除操作(一般都会返回被删除的元素)
1.队列方法描述
插入方法:
- add(E e) 添加成功返回true,失败抛IllegalStateException异常
- offer(E e) 成功返回 true,如果此队列已满,则等待指定时间后,若还不能加入,返回 false。
- put(E e) 将元素插入此队列的尾部,如果该队列已满,则一直阻塞
删除方法:
- remove(Object o) 移除指定元素,成功返回true,失败返回false
- poll() 获取并移除此队列的头元素,若队列为空,则等待指定时间后,若还不能获 取,则返回 null
- take() 获取并移除此队列头元素,若没有元素则一直阻塞。
检查方法:
- element() 获取但不移除此队列的头元素,没有元素则抛异常(调用peek())
- peek() 获取但不移除此队列的头;若队列为空,则返回 null。
二. ArrayBlockingQueue的基本使用
ArrayBlockingQueue 是一个用数组实现的有界阻塞队列,其内部按先进先出的原则对元素进行排序,其中put方法和take方法为添加和删除的阻塞方法
使用堵塞队列来非常简单地实现消费者生产者问题
public class ArrayBlockingQueueDemo {
private final static ArrayBlockingQueue<Apple> queue= new ArrayBlockingQueue<>(1);//大小为1的拥塞队列
public static void main(String[] args){
new Thread(new Producer(queue)).start();
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}
class Apple {
public Apple(){
}
}
/**
* 生产者线程
*/
class Producer implements Runnable{
private final ArrayBlockingQueue<Apple> mAbq;
Producer(ArrayBlockingQueue<Apple> arrayBlockingQueue){
this.mAbq = arrayBlockingQueue;
}
@Override
public void run() {
while (true) {
Produce();
}
}
private void Produce(){
try {
Apple apple = new Apple();
mAbq.put(apple);//如果满了,则会一直堵塞
System.out.println("生产:"+apple);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 消费者线程
*/
class Consumer implements Runnable{
private ArrayBlockingQueue<Apple> mAbq;
Consumer(ArrayBlockingQueue<Apple> arrayBlockingQueue){
this.mAbq = arrayBlockingQueue;
}
@Override
public void run() {
while (true){
try {
TimeUnit.MILLISECONDS.sleep(1000);
comsume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void comsume() throws InterruptedException {
Apple apple = mAbq.take();//如果为空则一直堵塞
System.out.println("消费Apple="+apple);
}
}
ArrayBlockingQueue内部的阻塞队列是通过重入锁ReenterLock和Condition条件队列实现的,所以ArrayBlockingQueue中的元素存在公平访问与非公平访问的区别
//默认非公平阻塞队列
ArrayBlockingQueue queue = new ArrayBlockingQueue(2);
//公平阻塞队列
ArrayBlockingQueue queue1 = new ArrayBlockingQueue(2,true);
三. ArrayBlockQueue的实现原理剖析
1. ArrayBlockingQueue原理概要
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
/** 存储数据的数组 */
final Object[] items;
/**获取数据的索引,指向队列头,主要用于take,poll,peek,remove方法 */
int takeIndex;
/**添加数据的索引,指向队列尾,主要用于 put, offer, or add 方法*/
int putIndex;
/** 队列元素的个数 */
int count;
/** 控制并非访问的锁 */
final ReentrantLock lock;
/**notEmpty条件对象,用于通知take方法队列已有元素,可执行获取操作 */
private final Condition notEmpty;
/**notFull条件对象,用于通知put方法队列未满,可执行添加操作 */
private final Condition notFull;
/**
迭代器
*/
transient Itrs itrs = null;
}
2. ArrayBlockingQueue的阻塞添加的实现原理
2.1 add方法
通过调用offer(E e)方法实现,若添加成功,则返回true,若添加失败,则抛出异常
2.2 offer方法
普通offer()方法:
public boolean offer(E e) {
checkNotNull(e);//判断e是否是null,若是,则抛出空指针异常
final ReentrantLock lock = this.lock;
lock.lock();//上不可中断锁
try {
if (count == items.length)//队列已满返回false
return false;
else {
enqueue(e);//加入队列
return true;
}
} finally {
lock.unlock();
}
}
堵塞延时的offer方法:
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
checkNotNull(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}
enqueue方法:
private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)//循环队列,指向数组头部
putIndex = 0;
count++;
notEmpty.signal();
}
2.3 put方法
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();//该方法可中断
try {
//当队列元素个数与数组长度相等时,无法添加元素
while (count == items.length)
//将当前调用线程挂起,添加到notFull条件队列中等待唤醒
notFull.await();
enqueue(e);//如果队列没有满直接添加。。
} finally {
lock.unlock();
}
}
3. ArrayBlockingQueue的阻塞移除实现原理
poll()方法
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
//判断队列是否为null,不为null执行dequeue()方法,否则返回null
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
dequeue方法
//删除队列头元素并返回
private E dequeue() {
//拿到当前数组的数据
final Object[] items = this.items;
@SuppressWarnings("unchecked")
//获取要删除的对象
E x = (E) items[takeIndex];
将数组中takeIndex索引位置设置为null
items[takeIndex] = null;
//takeIndex索引加1并判断是否与数组长度相等,
//如果相等说明已到尽头,恢复为0
if (++takeIndex == items.length)
takeIndex = 0;
count--;//队列个数减1
if (itrs != null)
itrs.elementDequeued();//同时更新迭代器中的元素数据
//删除了元素说明队列有空位,唤醒notFull条件对象添加线程执行添加操作
notFull.signal();
return x;
}
Taken()方法
//从队列头部删除,队列没有元素就阻塞,可中断
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();//中断
try {
//如果队列没有元素
while (count == 0)
//执行阻塞操作
notEmpty.await();
return dequeue();//如果队列有元素执行删除操作
} finally {
lock.unlock();
}
}
四. LinkedBlockingQueue的基本概要
LinkedBlockingQueue是一个由链表实现的有界队列阻塞队列,但大小默认值为Integer.MAX_VALUE,所以我们在使用LinkedBlockingQueue时建议手动传值,为其提供我们所需的大小,避免队列过大造成机器负载或者内存爆满等情况.
在正常情况下,链接队列的吞吐量要高于基于数组的队列(ArrayBlockingQueue),因为其内部实现添加和删除操作使用的两个ReenterLock来控制并发执行,而ArrayBlockingQueue内部只是使用一个ReenterLock控制并发,因此LinkedBlockingQueue的吞吐量要高于ArrayBlockingQueue
五. LinkedBlockingQueue的实现原理剖析
1. 添加方法的实现原理
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;//put锁
final AtomicInteger count = this.count;//队列元素数目,由于是两个锁来操作count,所以需要AtomicInteger来保证线程安全.
putLock.lockInterruptibly();//可中断上锁
try {
while (count.get() == capacity) {//队列已满则进入堵塞
notFull.await();
}
enqueue(node);//队列加入结点
c = count.getAndIncrement();//添加前元素的大小
if (c + 1 < capacity)
notFull.signal();//队列不满则,激活添加队列继续添加
} finally {
putLock.unlock();
}
if (c == 0)//c=0,说明消费队列已停止,需要激活
signalNotEmpty();
}
2. 移除方法的实现原理
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
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;
}
六. LinkedBlockingQueue和ArrayBlockingQueue异同
- 队列大小不同
- 数据存储容器不同
- 两者实现队列添加和移除的锁不一样,linked双锁且吞吐量大