03-阻塞队列实现原理
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(); // 划重点
}public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
// 这个while是必要的
while (count == items.length)
// 满了就放到notFull的等待队列
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x;
// 这是个循环数组
if (++putIndex == items.length)
putIndex = 0;
count++;
// 通知等待的消费者,有元素可以消费了
notEmpty.signal();
}DelayQueue
SynchronousQueue
最后更新于