前言
ArrayBlockingQueue 是一个用数组实现的有界阻塞队列. 此队列按照先进先出 (FIFO) 的原则对元素进行排序.
本文源码: 本文源码下载
例子
先通过一个简单的小例子看看其使用. 有三个生产者和两个消费者. 生产者负责生产数据, 消费者负责消费数据.
- package com.arrayblockingqueue;
- public class Test01 {
- static ArrayBlockingQueue<String> abq = new ArrayBlockingQueue(10);
- public static void main(String[] args) {
- Consumer consumer01 = new Consumer("consumer01");
- Consumer consumer02 = new Consumer("consumer02");
- Producer producer01 = new Producer("producer01");
- Producer producer02 = new Producer("producer02");
- Producer producer03 = new Producer("producer03");
- consumer01.start();
- consumer02.start();
- producer01.start();
- producer02.start();
- producer03.start();
- }
- static class Consumer extends Thread {
- Consumer(String name) {super(name);}
- public void run() {
- try {
- while (true) {
- System.out.println(Thread.currentThread().getName() + "gets" + abq.take());
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- }
- static class Producer extends Thread {
- Producer(String name) {super(name);}
- public void run() {
- try {
- for (int i = 0; i <3; i++) {
- abq.put(Thread.currentThread().getName() + "-" + i);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- }
- }
输出如下: 可以观察得到消费者们没有消费同一份数据.
- consumer01 gets producer01-0
- consumer01 gets producer02-0
- consumer01 gets producer02-1
- consumer01 gets producer02-2
- consumer01 gets producer01-1
- consumer01 gets producer01-2
- consumer01 gets producer03-0
- consumer02 gets producer03-1
- consumer02 gets producer03-2
实现思路
无并发情况
用数组实现一个 queue, 很明显需要一个头索引, 需要从头取数据, 也需要一个尾索引来加入新数据. 不了解的可以去做一下这道题 Design Circular Queue .
并发情况
在 ArrayBlockingQueue 中用了一个重入锁 ReentrantLock 和两个 Condition 来实现同步. 在操作数组的时候需要先获得锁, 当队列为空的时候通过 notEmpty.await()来使得线程休眠等待, 当队列满的时候通过 notFull.await()来使得线程休眠等待. 当有元素加入到队列中时使用 notEmpty.signal()来给线程发信号, 当有元素从队列中删除时使用 notFull.await()来给线程发信号.
源码
属性
- /** 存放数据的数组 */
- final Object[] items;
- /** 队列头的下标 */
- int takeIndex;
- /** 队列尾的下标 */
- int putIndex;
- /** 在队列中的元素个数 */
- int count;
- /**
- * Concurrency control uses the classic two-condition algorithm
- * found in any textbook.
- */
- /** 重入锁 */
- final ReentrantLock lock;
- /** Condition for waiting takes */
- private final Condition notEmpty;
- /** Condition for waiting puts */
- private final Condition notFull;
构造函数
- /**
- * @param capacity 队列的容量
- * @throws IllegalArgumentException if {@code capacity <1}
- */
- public ArrayBlockingQueue(int capacity) {
- this(capacity, false);
- }
- /**
- *
- * @param capacity 队列容量
- * @param fair 如果 fair 是 true, 表明锁是公平锁, 先等待的线程会先获得锁
- * @throws IllegalArgumentException if {@code capacity < 1}
- */
- public ArrayBlockingQueue(int capacity, boolean fair) {
- if (capacity <= 0)
- throw new IllegalArgumentException();
- this.items = new Object[capacity];
- lock = new ReentrantLock(fair);
- notEmpty = lock.newCondition();
- notFull = lock.newCondition();
- }
初始化上面的一些属性.
辅助方法
- transient Itrs itrs = null;
- // Internal helper methods
- /**
- * 环形的减少 index
- */
- final int dec(int i) {
- return ((i == 0) ? items.length : i) - 1;
- }
- /**
- * 取对应下标的元素
- */
- @SuppressWarnings("unchecked")
- final E itemAt(int i) {
- return (E) items[i];
- }
- /**
- * 如果 v 为 null 抛出空指针异常
- *
- * @param v the element
- */
- private static void checkNotNull(Object v) {
- if (v == null)
- throw new NullPointerException();
- }
- /**
- * Inserts element at current put position, advances, and signals.
- * Call only when holding lock.
- *
- * 加入一个元素并且给因为队列空而休眠等待的线程信号
- * 调用该方法有两个条件:
- * 1. 获得锁
- * 2. items[putIndex] = null
- *
- */
- private void enqueue(E x) {
- // assert lock.getHoldCount() == 1;
- // assert items[putIndex] == null;
- final Object[] items = this.items;
- items[putIndex] = x;
- if (++putIndex == items.length)
- putIndex = 0;
- count++;
- notEmpty.signal();
- }
- /**
- * 删除一个元素并且给因为队列满而休眠等待的线程信号
- * 调用该方法有两个条件:
- * 1. 获得锁
- * 2. items[takeIndex] != null
- * Extracts element at current take position, advances, and signals.
- * Call only when holding lock.
- */
- private E dequeue() {
- // assert lock.getHoldCount() == 1;
- // assert items[takeIndex] != null;
- final Object[] items = this.items;
- @SuppressWarnings("unchecked")
- E x = (E) items[takeIndex];
- items[takeIndex] = null;
- if (++takeIndex == items.length)
- takeIndex = 0;
- count--;
- // 关于 itrs 是跟遍历有关 不会影响整体逻辑
- if (itrs != null)
- itrs.elementDequeued();
- notFull.signal();
- return x;
- }
- /**
- * 删除下标为 removeIndex 的元素
- * 只有在获得锁才可以被使用
- */
- void removeAt(final int removeIndex) {
- // assert lock.getHoldCount() == 1;
- // assert items[removeIndex] != null;
- // assert removeIndex>= 0 && removeIndex <items.length;
- final Object[] items = this.items;
- if (removeIndex == takeIndex) {
- // removing front item; just advance
- items[takeIndex] = null;
- if (++takeIndex == items.length)
- takeIndex = 0;
- count--;
- if (itrs != null)
- itrs.elementDequeued();
- } else {
- // an "interior" remove
- // slide over all others up through putIndex.
- // 将 removeIndex 到 putIndex 这段区域的元素集体往前移一个单位
- final int putIndex = this.putIndex;
- for (int i = removeIndex;;) {
- int next = i + 1;
- if (next == items.length)
- next = 0;
- if (next != putIndex) {
- items[i] = items[next];
- i = next;
- } else {
- items[i] = null;
- this.putIndex = i;
- break;
- }
- }
- count--;
- if (itrs != null)
- itrs.removedAt(removeIndex);
- }
- notFull.signal();
- }
以上是一些辅助函数, 包括进出队列和删除某个下标对应的元素等等. 大部分上面的方法都是需要在已经获得锁的情况下才可以被调用.
加入元素
- /**
- * 向队列尾部插入该元素 如果队列已满没有空间则等待
- * 注意: 该方法响应中断
- * 有一种情况下会加入失败:
- * 1. 在获得锁或者因为队列满而导致休眠等待的过程中该线程被其他线程中断
- *
- * @throws InterruptedException {@inheritDoc}
- * @throws NullPointerException {@inheritDoc}
- */
- public void put(E e) throws InterruptedException {
- checkNotNull(e);
- final ReentrantLock lock = this.lock;
- lock.lockInterruptibly();
- try {
- while (count == items.length)
- notFull.await();
- enqueue(e);
- } finally {
- lock.unlock();
- }
- }
作用: 向队列尾部插入该元素 如果队列已满没有空间则等待.
有一种情况下会加入失败:
1. 在获得锁或者因为队列满而导致休眠等待的过程中该线程被其他线程中断.
另外关于 poll 类的方法原理基本一致.
消费元素
- /**
- * 如果当前队列元素为 0, 则等待
- * 返回一个从队列中取出来的元素
- * 有一种情况下会消费失败:
- * 1. 在获得锁或者因为队列空而导致休眠等待的过程中该线程被其他线程中断
- * @return
- * @throws InterruptedException
- */
- public E take() throws InterruptedException {
- final ReentrantLock lock = this.lock;
- lock.lockInterruptibly();
- try {
- while (count == 0)
- notEmpty.await();
- return dequeue();
- } finally {
- lock.unlock();
- }
- }
此 take 与 put 方法对应, 取出队列中最早放进去的元素.
有一种情况下会消费失败:
1. 在获得锁或者因为队列空而导致休眠等待的过程中该线程被其他线程中断.
对应 offer 的是 poll, 原理基本一致, 不多说了.
删除元素
- /**
- * 删除元素 o
- * 如果队列中有多个元素 o, 只删除第一个找到的第一个元素
- *
- * @param o 需要删除的元素 o
- * @return {@code true} 如果操作后对该队列有改变则返回 true
- */
- public boolean remove(Object o) {
- if (o == null) return false;
- final Object[] items = this.items;
- final ReentrantLock lock = this.lock;
- lock.lock();
- try {
- if (count> 0) {
- final int putIndex = this.putIndex;
- int i = takeIndex;
- do {
- if (o.equals(items[i])) {
- removeAt(i);
- return true;
- }
- if (++i == items.length)
- i = 0;
- } while (i != putIndex);
- }
- return false;
- } finally {
- lock.unlock();
- }
- }
只是在常规删除操作外加了个锁, 很简单.
遍历元素
在 ArrayBlockingQueue 中的遍历与其他的遍历有所不同, 这个需要一定的篇幅来分析, 会在后续的博客中有专门分析.
参考
1. Java1.8 源码.
来源: http://www.jianshu.com/p/e0b916aef771