//阻塞式数组队列
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
//存放元素数组
final Object[] items;
/** items index for next take, poll, peek or remove */
int takeIndex;
/** items index for next put, offer, or add */
int putIndex;
//队列中元素数量
int count;
//可重入锁
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
//添加元素,当队列满时,等待
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();
}
}
private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x;
// 放入后存元素的索引等于数组长度,表示已满
if (++putIndex == items.length)
putIndex = 0;
count++;
// 唤醒在notEmpty条件上等待的线程
notEmpty.signal();
}
//取元素,当队列为空时,会阻塞一直等待
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)//队列数组元素个数为0,阻塞等待
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
private E dequeue() {
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条件上等待的线程
notFull.signal();
return x;
}
}
ArrayBlockingQueue源码阅读
最新推荐文章于 2024-05-16 19:37:55 发布