概述
ArrayBlockingQueue使用数组实现的有界阻塞队列,初始化是必须指定容量。是FIFO先进先出队列,支持公平锁和非公平锁。
使用的例子就不放了,在github中都有
类结构
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
//存储元素的数组
final Object[] items;
//下一个出队方法移出的元素位置,即调用take就是将items[takeIndex]移除
int takeIndex;
//下一个入队方法加入的元素位置
int putIndex;
//队列现在的数量,因为入队出队都加lock不会有竞争问题,所以普通int已经足够
int count;
//重入锁,入队出队前都要加lock锁定
final ReentrantLock lock;
//队列为空时,take出队方法等待
private final Condition notEmpty;
//队列满时,put入队方法等待
private final Condition notFull;
。。。
}
构造方法
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
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();
}
可以看到构造方法必须传入capacity,这个参数时什么意思?这个参数就是数组的容量,即数组只能容纳这么多节点,如果超过容量怎么办?根据前面阻塞队列简介文章的介绍,要看调用的是哪个入队方法,offer是直接返回false,入队不成功,即丢弃掉。put是阻塞线程等队列有空间了入队成功再返回。add方法会抛出异常。
构造方法还有个可选参数fair, 这个表明构造的是公平锁还是非公平锁。
offer方法
public boolean offer(E e) {
//节点元素不允许为空
checkNotNull(e);
final ReentrantLock lock = this.lock;
//加重入锁
lock.lock();
try {
//队列满了直接返回false
if (count == items.length)
return false;
else {
//进行入队操作
enqueue(e);
return true;
}
} finally {
lock.unlock();
}
}
enqueue 方法
private void enqueue(E x) {
//putIndex就是本次入队的数组下标值
final Object[] items = this.items;
//入队元素的引用赋值给items[putIndex]
items[putIndex] = x;
//下标值越界,将下标重新等于0,逻辑上的环形数组
if (++putIndex == items.length)
putIndex = 0;
count++;
//唤醒等待出队的线程
notEmpty.signal();
}
put方法
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
//和offer方法不同的是队列满时,线程进入条件等待
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
add 方法
public boolean add(E e) {
return super.add(e);
}
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
可以看到add方法,队列入队失败后,会抛出IllegalStateException异常
poll方法
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
//队列为空时返回null,否则将队列元素出队
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
dequeue 方法
private E dequeue() {
// 将items[takeIndex]元素返回,并将items[takeIndex]引用赋为null
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];
items[takeIndex] = null;
//如果出队下标越界,赋值为0,逻辑上的环形数组
if (++takeIndex == items.length)
takeIndex = 0;
count--;
//该对象在迭代器即阻塞队列之间共享了数据,在队列删除元素时会更新迭代器
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
take 方法
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
//出队时,如果队列空,线程进行条件等待
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}