為什么BlockingQueue適合作為進行線程間安全的數(shù)據(jù)共享的通道流济?而高性能隊列例如:ConcurrentLinkedQueue不適合呢系吩?
- 關(guān)鍵在于Blocking上面,即阻塞:
- 當隊列為空:進行取操作的線程,會被阻塞(相比循環(huán)監(jiān)測,更省資源)蚁孔,并且當隊列中有元素后,線程會被自動喚醒惋嚎。
- 當隊列滿時:和上面類似杠氢。
BlockingQueue作為接口,有一系列滿足不同需求的實現(xiàn)類另伍,下面以容量固定的ArrayBlockingQueue為例鼻百,進行源碼分析,看看為什么這么神奇摆尝。
主要體現(xiàn)在take()和put()方法上温艇。
take():可以看到,當隊列為空的時候堕汞,線程會進行等待勺爱,下面還有一個重要的dequeue()方法。
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
/**
* Extracts element at current take position, advances, and signals.
* Call only when holding lock.
*/
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];
items[takeIndex] = null;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
在dequeue()方法中讯检,一旦有元素取出琐鲁,就會通知等待在notFull上面的線程卫旱,讓他們繼續(xù)工作。
- put()方法類似围段,不再贅述顾翼。。奈泪。
/**
* Inserts the specified element at the tail of this queue, waiting
* for space to become available if the queue is full.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
/**
* Inserts element at current put position, advances, and signals.
* Call only when holding lock.
*/
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();
}