LinkedBlockingQueue簡介


LinkedBlockingQueue是一個單向鏈表實現的阻塞隊列,先進先出的順序。支持多線程並發操作。

相比於數組實現的ArrayBlockingQueue的有界,LinkedBlockingQueue可認為是無界隊列。多用於任務隊列。

定義

LinkedBlockingQueue繼承AbstractQueue,實現了BlockingQueue,Serializable接口。內部使用單向鏈表存儲數據。

默認初始化容量是Integer最大值。

插入和取出使用不同的鎖,putLock插入鎖,takeLock取出鎖,添加和刪除數據的時候可以並行。多CPU情況下可以同一時刻既消費又生產。

源碼分析

jdk1.7.0_71

put(E)方法

向隊列尾部添加元素,隊列已滿的時候,阻塞等待。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();

int c = -1;
Node<E> node = new Node(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {

while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}

offer(E)方法

向隊列尾部添加元素,隊列已滿的時候,直接返回false。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
final AtomicInteger count = this.count;
if (count.get() == capacity)
return false;
int c = -1;
Node<E> node = new Node(e);
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
if (count.get() < capacity) {
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
}
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
return c >= 0;
}

不做過多分析,發現下面參考處的文章寫得不錯,建議看下。

參考

http://www.jianshu.com/p/cc2281b1a6bc


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM