Jdk1.6 JUC源码解析(13)-LinkedBlockingQueue
生活随笔
收集整理的這篇文章主要介紹了
Jdk1.6 JUC源码解析(13)-LinkedBlockingQueue
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
功能簡(jiǎn)介:
- LinkedBlockingQueue是一種基于單向鏈表實(shí)現(xiàn)的有界的(可選的,不指定默認(rèn)int最大值)阻塞隊(duì)列。隊(duì)列中的元素遵循先入先出 (FIFO)的規(guī)則。新元素插入到隊(duì)列的尾部,從隊(duì)列頭部取出元素。(在并發(fā)程序中,基于鏈表實(shí)現(xiàn)的隊(duì)列和基于數(shù)組實(shí)現(xiàn)的隊(duì)列相比,往往具有更高的吞吐 量,但性能稍差一些)
- 首先看下LinkedBlockingQueue內(nèi)部的數(shù)據(jù)結(jié)構(gòu):
首先可見(jiàn),內(nèi)部為單向鏈表;其次,內(nèi)部為兩把鎖:存鎖和取鎖,并分別關(guān)聯(lián)一個(gè)條件(是一種雙鎖隊(duì)列)。
- 還是從put和take入手,先看下put方法:
? ? ? ?代碼很容易看懂,再看下take方法實(shí)現(xiàn):
public E take() throws InterruptedException {E x;int c = -1;final AtomicInteger count = this.count;final ReentrantLock takeLock = this.takeLock;takeLock.lockInterruptibly();try {try {while (count.get() == 0)notEmpty.await();} catch (InterruptedException ie) {notEmpty.signal(); // propagate to a non-interrupted threadthrow ie;}x = extract();c = count.getAndDecrement();if (c > 1)notEmpty.signal();} finally {takeLock.unlock();}if (c == capacity)signalNotFull();return x;}/*** Removes a node from head of queue,* @return the node*/private E extract() {Node<E> first = head.next;head = first;E x = first.item;first.item = null;return x;}/*** Signals a waiting put. Called only from take/poll.*/private void signalNotFull() {final ReentrantLock putLock = this.putLock;putLock.lock();try {notFull.signal();} finally {putLock.unlock();}}?? ? ? 和put對(duì)等的邏輯,也很容易看懂。
- 上面看到,主要方法里并沒(méi)有同時(shí)用兩把鎖,但有些方法里會(huì)同時(shí)使用兩把鎖,比如remove方法等:
總結(jié)
以上是生活随笔為你收集整理的Jdk1.6 JUC源码解析(13)-LinkedBlockingQueue的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux软件包管理-rpm
- 下一篇: S2SH整合所需jar包及其详解