ArrayBlockingQueue源码阅读与理解
简介:FIFO队列,运用重入锁配合Condition控制多线程进出,算法:运用一个Object数组,插入顺序0->length->0满了则等待,0->length->0逐个取空了想取也等待。
几个变量:
//数据存储
final Object[] items;
//取数据指针
int takeIndex;
//放数据指针
int putIndex;
//个数
int count;
//重入锁
final ReentrantLock lock;
//队列空的时候,重入的情况下,取数据就会进入notEmpty等待队列
private final Condition notEmpty;
//队列满的时候,重入的情况下,插入数据就会进入notFull等待队列
private final Condition notFull;
//迭代器对象
transient Itrs itrs = null;
几个方法:
//插入队尾
public boolean add(E e) {
return super.add(e);
}
public boolean offer(E e) {
checkNotNull(e);
final ReentrantLock lock = this.lock;
//上锁
lock.lock();
try {
//队列满了
if (count == items.length)
return false;
//入队
else {
enqueue(e);
return true;
}
} finally {
//锁消除
lock.unlock();
}
}
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
//赋值
items[putIndex] = x;
//队列满了index返回0
if (++putIndex == items.length)
putIndex = 0;
count++;
//唤醒一个等待取值队列
notEmpty.signal();
}
//插入队尾
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();
}
}
//弹出
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
//出队
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;
//满了则index又返回0
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
//唤醒一个等待插入队列
notFull.signal();
return x;
}