linkedblockingqueue在java中的原理

2026-01-29 0 44,994

我们在说队列顺序的时候,linkedblockingqueue先进先出的顺序,显示和我们常规的先进再出的理念有所不同。这里我们需要深入到linkedblockingqueue的原理中,去讨论这种顺序机制的存在。接下来我们会从其主要属性、构造函数以及继承结构中,为大家找寻linkedblockingqueu的原理。

1.主要属性

// 容量
private final int capacity;
 
// 元素数量
private final AtomicInteger count = new AtomicInteger();
 
// 链表头
transient Node head;
 
// 链表尾
private transient Node last;
 
// take锁
private final ReentrantLock takeLock = new ReentrantLock();
 
// notEmpty条件
// 当队列无元素时,take锁会阻塞在notEmpty条件上,等待其它线程唤醒
private final Condition notEmpty = takeLock.newCondition();
 
// 放锁
private final ReentrantLock putLock = new ReentrantLock();
 
// notFull条件
// 当队列满了时,put锁会会阻塞在notFull上,等待其它线程唤醒
private final Condition notFull = putLock.newCondition();

1)capacity,有容量,可以理解为LinkedBlockingQueue是有界队列

2)head, last,链表头、链表尾指针

3)takeLock,notEmpty,take锁及其对应的条件

4)putLock, notFull,put锁及其对应的条件

(5)入队、出队使用两个不同的锁控制,锁分离,提高效率

2.构造函数

public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);
}
 
// 限制队列容量,并初始化队列的 head 和 last 节点.
public LinkedBlockingQueue(int capacity) {
    if (capacity <= 0) throw new IllegalArgumentException();
    this.capacity = capacity;
    last = head = new Node(null);
}
 
// LinkedBlockingQueue(int capacity)初始化,然后加写锁,将集合c一个个入队.
public LinkedBlockingQueue(Collection c) {
    this(Integer.MAX_VALUE);
    final ReentrantLock putLock = this.putLock;
    putLock.lock(); // 写锁(以重入锁实现,对队尾的插入进行控制)
    try {
        int n = 0;
        for (E e : c) {
        	// null元素抛出异常
            if (e == null)
                throw new NullPointerException();
            if (n == capacity)
                throw new IllegalStateException("Queue full");
            enqueue(new Node(e)); //将元素封装成Node,入队
            ++n;
        }
        count.set(n);
    } finally {
        putLock.unlock(); // 释放
    }
}

3.继承结构

以上就是linkedblockingqueue在java中的原理展示,我们通过其函数组成和结构示意图,对linkedblockingqueue能够有大体上的了解,尤其是我们说它是链表结构,想必现在大家已经能够理解原理了。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 java教程 linkedblockingqueue在java中的原理 https://www.zhiup.top/11041.html

相关