您的位置:首页 > 产品设计 > UI/UE

ArrayBlockingQueue源码阅读

2016-08-12 21:18 495 查看
//阻塞式数组队列
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdk