【Java】之 ArrayBlockingQueue 浅析


一、简介


ArrayBlockingQueue 是一个先进先出队列,维护takeIndexputIndex两个指针,可循环使用数组。

  1. 线程安全
  2. 一定初始化数组后,数组长度就不能改变

(1)方法

方法抛出异常返回特殊值阻塞超时退出
插入add()offer()put()offer(e, time, unit)
移除remove()poll()take()poll(time, unit)


二、源码分析


在这里插入图片描述

(1)put()

public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    // 若线程中断,则抛异常
    lock.lockInterruptibly();
    try {
        // 若队列满,则等待,加入`condition`队列
        while (count == items.length)
            notFull.await();
        enqueue(e);
    } finally {
        lock.unlock();
    }
}

(2)take()

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        // 若队列没有数据,则等待,加入`condition`队列
        while (count == 0)
            notEmpty.await();
        return dequeue();
    } finally {
        lock.unlock();
    }
}


三、应用场景


可用于 生产者消费者模型。

public class ArrayBlockingQueueTest {

    private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

    public static void main(String[] args) {

        ArrayBlockingQueueTest test = new ArrayBlockingQueueTest();

        Consumer consumer = test.new Consumer();
        Producer producer = test.new Producer();

        consumer.start();
        producer.start();
    }

    class Consumer extends Thread {
        @Override
        public void run() {

            try {

                Integer num = queue.take();

                System.out.println(Thread.currentThread().getName() + " 拿到数字: " + num);

            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
    }

    class Producer extends Thread {

        @Override
        public void run() {

            try {

                int num = 1;

                queue.put(num);

                System.out.println(Thread.currentThread().getName()  + " 放入数字: " + num);

            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
    }
}

如图:
在这里插入图片描述

输出可能乱序

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值