阻塞队列
当线程往队列里放,队列已满,等待队列不满条件(notFull)满足后线程才能继续
当线程往队列里取,队列已空,等待队列不空条件(notEmpty)满足后线程才能继续
/** 队列不空条件 */
private final Condition notEmpty;
/** 队列不满条件 */
private final Condition notFull;
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
//ArrayBlockingQueue中lock的2个condition
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
//如果count达到了数组的长度,即队列已满,则队列不满条件等待
//多个线程在这里休眠等待队列不满条件条件满足后唤醒,唤醒队列
//会重新竞争锁
notFull.await();
//获得锁的继续插入
enqueue(e);
} finally {
lock.unlock();
}
}
private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x;
//有界队列,到putIndex到数组头了,就返回来
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
//如果count为0,即队列已空,则队列不空条件等待
//多个线程在这里休眠等待队列不空条件满足后唤醒
//会重新竞争锁
notEmpty.await();
//获得锁的继续取
return dequeue();
} finally {
lock.unlock();
}
}
private E dequeue() {
final Object[] items = this.items;
E x = (E) items[takeIndex];
items[takeIndex] = null;
//takeIndex到头了,返回0
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
源码比较简单,也是一个对lock和condition的知识点的加深理解。