1. 程式人生 > >25、Java並發性和多線程-阻塞隊列

25、Java並發性和多線程-阻塞隊列

多線程 throws clas cep ted this return exception exceptio

以下內容轉自http://ifeve.com/blocking-queues/:

阻塞隊列與普通隊列的區別在於,當隊列是空的時,從隊列中獲取元素的操作將會被阻塞,或者當隊列是滿時,往隊列裏添加元素的操作會被阻塞。試圖從空的阻塞隊列中獲取元素的線程將會被阻塞,直到其他的線程往空的隊列插入新的元素。同樣,試圖往已滿的阻塞隊列中添加新元素的線程同樣也會被阻塞,直到其他的線程使隊列重新變得空閑起來,如從隊列中移除一個或者多個元素,或者完全清空隊列,下圖展示了如何通過阻塞隊列來合作:

技術分享

線程1往阻塞隊列中添加元素,而線程2從阻塞隊列中移除元素

從5.0開始,JDK在java.util.concurrent包裏提供了阻塞隊列的官方實現。盡管JDK中已經包含了阻塞隊列的官方實現,但是熟悉其背後的原理還是很有幫助的。

阻塞隊列的實現

阻塞隊列的實現類似於帶上限的Semaphore的實現。下面是阻塞隊列的一個簡單實現

public class BlockingQueue {

  private List queue = new LinkedList();
  private int  limit = 10;

  public BlockingQueue(int limit){
    this.limit = limit;
  }


  public synchronized void enqueue(Object item) throws InterruptedException  {
    
while(this.queue.size() == this.limit) { wait(); } if(this.queue.size() == 0) { notifyAll(); } this.queue.add(item); } public synchronized Object dequeue() throws InterruptedException{ while(this.queue.size() == 0){ wait(); } if(this.queue.size() == this
.limit){ notifyAll(); } return this.queue.remove(0); } }

必須註意到,在enqueue和dequeue方法內部,只有隊列的大小等於上限(limit)或者下限(0)時,才調用notifyAll方法。如果隊列的大小既不等於上限,也不等於下限,任何線程調用enqueue或者dequeue方法時,都不會阻塞,都能夠正常的往隊列中添加或者移除元素。

25、Java並發性和多線程-阻塞隊列