Jdk1.6 JUC源码解析(13)-LinkedBlockingQueue
生活随笔
收集整理的這篇文章主要介紹了
Jdk1.6 JUC源码解析(13)-LinkedBlockingQueue
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
功能簡介:
- LinkedBlockingQueue是一種基于單向鏈表實現的有界的(可選的,不指定默認int最大值)阻塞隊列。隊列中的元素遵循先入先出 (FIFO)的規則。新元素插入到隊列的尾部,從隊列頭部取出元素。(在并發程序中,基于鏈表實現的隊列和基于數組實現的隊列相比,往往具有更高的吞吐 量,但性能稍差一些)
- 首先看下LinkedBlockingQueue內部的數據結構:
首先可見,內部為單向鏈表;其次,內部為兩把鎖:存鎖和取鎖,并分別關聯一個條件(是一種雙鎖隊列)。
- 還是從put和take入手,先看下put方法:
? ? ? ?代碼很容易看懂,再看下take方法實現:
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對等的邏輯,也很容易看懂。
- 上面看到,主要方法里并沒有同時用兩把鎖,但有些方法里會同時使用兩把鎖,比如remove方法等:
總結
以上是生活随笔為你收集整理的Jdk1.6 JUC源码解析(13)-LinkedBlockingQueue的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux软件包管理-rpm
- 下一篇: S2SH整合所需jar包及其详解