首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Java集合之阻塞队列ArrayBlockingQueue

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;

}

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200211A0NITE00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券