JDK阻塞队列--ArrayBlockingQueue、LinkedBlockingQueue

11 篇文章 0 订阅

ArrayBlockingQueue

基本数据结构

/** The queued items  任务队列*/
final Object[] items;

/**任务队列中实际的任务数 <=items.length */
int count;

/** Main lock guarding all access */
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 {
        //如果当前队列已满,则线程会在notFull队列阻塞等待
        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 {
        //如果队列为空,没有数据,将消费者线程阻塞在notEmpty,直到被signal唤醒
        while (count == 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;
}

//队列剩余空间
public int remainingCapacity() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return items.length - count;
    } finally {
        lock.unlock();
    }
}
  • put、take通过condition通知机制来完成可阻塞的插入和获取数据

LinkedBlockingQueue

  • 与ArrayBlockingQueue主要区别,LinkedBlockingQueue插入和删除时分别由两个lock(takeLock和putLock)控制线程安全,也由这两个lock生成两个对应的condition(notEmpty和notFull)实现可阻塞的插入和删除数据。采用链表来实现队列。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值