栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

linkedblockingqueue在java中的原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

linkedblockingqueue在java中的原理

我们在说队列顺序的时候,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能够有大体上的了解,尤其是我们说它是链表结构,想必现在大家已经能够理解原理了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/15165.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号