阻塞队列之 LinkedBlockingQueue分析探究

LinkedBlockingQueue详解
本文深入解析了Java并发包中的LinkedBlockingQueue数据结构,包括其内部实现机制如链表结构、锁分离策略、条件变量等,并介绍了核心方法如offer、put、poll、take等的工作原理。

阻塞队列

LinkedBlockingQueue

  • 内部使用Node 节点组成一个单链表
  • head 、 last 并且保存了头尾节点、
  • takeLock = new ReentrantLock();
    • 删除的时候锁
  • putLock = new ReentrantLock();
    • 存放的时候锁
  • notEmpty = takeLock.newCondition();
    • 不为空时候的newCondition
  • notFull = putLock.newCondition();
    • 不满时候的newCondition
  • capacity 容量
public class LinkedBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
   
   
  
    static class Node<E> {
   
   
        E item;
        Node<E> next;
        Node(E x) {
   
    item = x; }
    }
    private final int capacity;
    private final AtomicInteger count = new AtomicInteger();
    transient Node<E> head;
    private transient Node<E> last;
    private final ReentrantLock takeLock = new ReentrantLock();
    private final Condition notEmpty = takeLock.newCondition();
    private final ReentrantLock putLock = new ReentrantLock();
    private final Condition notFull = putLock.newCondition();
}

构造函数

默认的无参调用有参,并且使用 Integer的最大值。

    public LinkedBlockingQueue() {
   
   
        this(Integer.MAX_VALUE);
    }

直接把 容量设置为 Integer的最大值。并且初始化 队列, 设置头尾节点。

    public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node<E>(null);
    }

初始化之后的结构如下

类中的方法

  • 可以看到类中的方法和 ArrayBlockingQueue 中类似
    • 都是一些入队出队的方法
      • 毕竟上层接口也是 Queue

添加元素

add 方法
  • 在这里面会调用 offer 方法来做出实现
    • 因为它们(LinkedBlockingQueue、ArrayBlockingQueue )是 AbstractQueue 的子类 所以在一些方法的调用流程上都是差不多的,走父类的方法,然后在用自己的具体实现。
  • offer 方法 为false的时候,会抛出异常。
    public boolean add(E e) {
   
   
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }
LinkedBlockingQueue
offer方法的具体实现
  • 判断要添加的元素是不是为空

  • 然后取出当前队列的大小

    • 如果大小已经等于容量(已经满了) 直接 false
    public boolean offer(E e) {
   
   
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
        if (count.get() == capacity)
            
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值