在多執行緒程式設計中,wait()和notify()是用於線程同步。本文介紹如何使用 wait() 和 notification() 實作阻塞佇列,這是允許執行緒阻塞直到有項可用或空間可用的資料結構。
條件阻塞:
Java代碼:
public class BlockingQueue<T> { private Queue<T> queue = new LinkedList<>(); private int capacity; public BlockingQueue(int capacity) { this.capacity = capacity; } public synchronized void put(T element) throws InterruptedException { while (queue.size() == capacity) { wait(); } queue.add(element); notify(); // notifyAll() for multiple producer/consumer threads } public synchronized T take() throws InterruptedException { while (queue.isEmpty()) { wait(); } T item = queue.remove(); notify(); // notifyAll() for multiple producer/consumer threads return item; } }
Java 1.5 並發庫
Java 1.5引入了一個並發庫,提供了更高級別的抽象:
修改後的阻塞隊列實現:public class BlockingQueue<T> { private Queue<T> queue = new LinkedList<>(); private int capacity; private Lock lock = new ReentrantLock(); private Condition notFull = lock.newCondition(); private Condition notEmpty = lock.newCondition(); public BlockingQueue(int capacity) { this.capacity = capacity; } public void put(T element) throws InterruptedException { lock.lock(); try { while (queue.size() == capacity) { notFull.await(); } queue.add(element); notEmpty.signal(); } finally { lock.unlock(); } } public T take() throws InterruptedException { lock.lock(); try { while (queue.isEmpty()) { notEmpty.await(); } T item = queue.remove(); notFull.signal(); return item; } finally { lock.unlock(); } } }
以上是如何使用 wait() 和 notify() 在 Java 中實作阻塞佇列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!