Java阻塞队列poll_java阻塞队列之LinkedBlockingQueue

本文详细介绍了Java阻塞队列LinkedBlockingQueue的构造函数、内部结构、节点类Node以及各种添加和取出元素的方法,如put、take、offer和poll。LinkedBlockingQueue使用单向链表实现,通过putLock和takeLock两把锁实现并发控制,确保线程安全。
摘要由CSDN通过智能技术生成

LinkedBlockingQueue是BlockingQueue中的其中一个,其实现方式为单向链表,下面看其具体实现。(均为JDK8)

一、构造函数

在LinkedBlockingQueue中有三个构造函数,如下图,

1aa43f22cb3b61463bb7ac6f12febcec.png

1、LinkedBlockingQueue()

这是一个无参的构造函数,其定义如下,

publicLinkedBlockingQueue() {this(Integer.MAX_VALUE);

}

在这个构造函数中调用了有参的构造函数,传入的整型值为Integer所能表示的最大值(0x7fffffff)。下面看这个带参数的构造方法。

2、LinkedBlockingQueue(int capacity)

这是一个整型参数的构造方法其,定义如下,

public LinkedBlockingQueue(intcapacity) {if (capacity <= 0) throw newIllegalArgumentException();this.capacity =capacity;

last= head = new Node(null);

}

从其实现上来看,其整型参数代表此队列的容量,即元素的最大个数;然后初始化了last和head两个变量,我们猜last应该是此队列的尾元素、head为此队列的头元素。这里有一个Node类,下面看Node类的实现,

static class Node{

E item;/*** One of:

* - the real successor Node

* - this Node, meaning the successor is head.next

* - null, meaning there is no successor (this is the last node)*/Nodenext;

Node(E x) { item=x; }

}

Node是LinkedBlockingQueue的静态内部类,也是组成此队列的节点元素,其内部有两个属性,一个Item代表节点元素,next指向下一个Node节点,这样就可以得出LinkedBlockingQueue的结构是使用Node连接起来,头节点为head,尾节点为last。

2beafad19390cf15b9540c22558400cd.png

3、LinkedBlockingQueue(Collection extends E> c)

此构造方法是使用一个集合类进行构造,其定义如下

public LinkedBlockingQueue(Collection extends E>c) {this(Integer.MAX_VALUE);final ReentrantLock putLock = this.putLock;

putLock.lock();//Never contended, but necessary for visibility

try{int n = 0;for(E e : c) {if (e == null)throw newNullPointerException();if (n ==capacity)throw new IllegalStateException("Queue full");

enqueue(new Node(e));++n;

}

count.set(n);

}finally{

putLock.unlock();

}

}

4、LinkedBlockingQueue的属性

从上面的构造函数中可以大体了解其属性有容量(capacity),队列中的元素数量(count)、头节点(head)、尾节点(last)等,如下

/**The capacity bound, or Integer.MAX_VALUE if none*/

private final intcapacity;/**Current number of elements*/

private final Atom

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值