BlockingQueue原理解析

方法功能表

功能抛出异常返回特殊值超时阻塞
新增add(e)offer()offer(timeout)put(e)
删除remove()poll()poll(timeout)take()
查询element()peek()

这些方法都使用了 ReentrantLock,所以BlockingQueue是线程安全的( add()方法不是 )

利用方法的阻塞性,可以很方便的实现生产者—消费者

说明:

1、offer() 增加元素,有可用的空间,返回true,否通返回false

  public boolean offer(E e) {
        Objects.requireNonNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

2、put 添加元素,没有可用的空间是,添加的线程一直等待(阻塞),直到有空余的空间,或者程序异常

public void put(E e) throws InterruptedException {
        Objects.requireNonNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

3.take() 返回并删除队列的头元素,也是一个阻塞的方法

   public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

4、 add方法 不是线程安全

public boolean add(E e) {
        return super.add(e);  //调用的是AbstractQueue的方法,
}
             ?(上面调用下面)
AbstractQueue的方法
public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值