BlockingDeque,BlockingQueue,jdk源码阅读(五)

BlockingQueue:阻塞队列(单项)
BlockingDeque:阻塞队列(双向)
在这里插入图片描述

阻塞队列使用:
使用方法和集合大同小异
API:
在这里插入图片描述
源码分析
ArrayBlockingQueue:

  1. 构造方法
public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }
public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        //初始化一个数组
        this.items = new Object[capacity];
        //初始化ReentrantLock锁
        lock = new ReentrantLock(fair);
        //相当于消费者
        notEmpty = lock.newCondition();
        //相当于生产者
        notFull =  lock.newCondition();
    }    			
  1. void put(E e)
//    添加元素到队列(一直阻塞)
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
//        lockInterruptibly()是加锁可以被中断的一种机制
        lock.lockInterruptibly();
        try {
//         如果数组满了,相当于生产者不用在生产了,所以阻塞生产者
            while (count == items.length)
                notFull.await();
//            添加元素到队列
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }
  1. void enqueue(E x)
//    添加元素到队列
    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();
    }
  1. E take()
//    移除元素
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
//                数组元素为0,相当于没有产品了,所以需要阻塞消费者
                notEmpty.await();
//            移除元素
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
  1. E 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--;
//        itrs是一个迭代器,如果存在的话也需要同步更新
        if (itrs != null)
            itrs.elementDequeued();
//        消费者消费了产品,所以需要生产者继续生产,所以唤醒生产者
        notFull.signal();
        return x;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值