下面我们来说一下ArraryBlockingQueue,之前我们说过,LinkedBlockingQueue是基于链表实现的,那么ArrayBlockingQueue就是基于数组实现的,我们来看一下ArrayBlockingQueue是怎么实现的。
ArrayBlockingQueue里有一个属性items
/** The queued items */
final Object[] items;
这是一个对象数组,ArrayBlockingQueue的元素就存储在对象数组里。
我们来看一下put方法
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();
}
}
基本和LinkedBlockingQueue差不多,也是先上锁,然后如果数组的元素数量等于容量,则阻塞当前线程,然后放入数组中,然后解锁。我们来看一下enqueue方法
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();
}
首先将元素放到putIndex位置上,然后putIndex++,判断putIndex是否等于容量,如果等于则将putIndex重置为0,然后唤醒take方法阻塞的线程
再来看一下take方法
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
也是先加锁,然后如果元素的数量等于0,则阻塞当前线程,然后从数组中取出元素返回,然后解锁。再来看一下dequeue方法
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;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
先去数组对应位置上取出元素,然后takeIndex++,如果takeIndex等于容量,则将takeIndex重置为0,然后唤醒put方法阻塞的线程
ArrayBlockingQueue的分析就到这里了。
网友评论