工作过程
基础数据结构Object[]数组,遵循先入先出(FIFO)的原则,它是一个基于生产者和消费者模型的有界的队列。
出队入队源码:
/** Main lock guarding all access */
final ReentrantLock lock;//可重入锁
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
/** 队列里存入null,抛空指针异常
* Throws NullPointerException if argument is 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.
*/
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();//唤醒
}
/** 出队操作
* 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--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();//唤醒
return x;
}
//出队操作 : 队列里的元素已经被消费者消费完,等待生产。
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();//堵塞
return dequeue();
} finally {
lock.unlock();
}
}
//入队操作 :队列里的元素已经被生产者填满,等待消费。
/**
* Inserts the specified element at the tail of this queue, waiting
* for space to become available if the queue is full.
*
* @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();
}
}
使用提示:ArrayBlockingQueue结合线程池一起使用实现并行业务处理的需求非常高效,ArrayBlockingQueue#take取出的对象用作null表示等待处理。