ArrayBlockingQueue是数组实现方式的阻塞队列,用Object[] items 数组存储数据,用takeIndex和putIndex标记存放和获取数据的位置。
先看下继承关系,继承于AbstractCollection并实现了BlockingQueue接口:
ArrayBlockingQueue
先看看put的逻辑:
1、检查e是否为空,如果为空,抛出NullPointerException异常
2、获取锁,如果队列满了,等待,如果没满,入队
3、释放锁
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();
}
}
看下入队的逻辑:
1、把数据放到putIndex位置,putIndex++,如果putIndex和数组长度一样,把putIndex赋值为0,
2、唤醒出队等待线程
private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();
}
以下是take的逻辑:
1、获取锁,如果队列为空,等待,如果不为空,出队
2、释放锁
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
出队的逻辑:获取takeIndex位置的元素,把数组中的元素置空,takeIndex++,如果大于数组长度,takeIndex归零,唤醒入队等等线程
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.signal();
return x;
}
领取专属 10元无门槛券
私享最新 技术干货