Using Wait() and Notify() in Java: A Scenario with Queues
Question:
Can you provide a comprehensive walkthrough of how to implement the wait() and notify() methods with a Queue?
Answer:
Principle of Wait() and Notify()
Wait() and notify() enable thread coordination by having threads wait for specific conditions to be met before proceeding. In this case, we're interested in creating a blocking queue that enforces capacity limitations.
Implementation
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(); // Notify waiting threads } public synchronized T take() throws InterruptedException { while (queue.isEmpty()) { wait(); } T item = queue.remove(); notify(); // Notify waiting threads return item; } }
How It Works
Note: Ensure that the wait() and notify() calls are synchronized on the same object and placed within a while loop to handle spurious wake-ups.
Java 1.5 Concurrent Features
Java 1.5 introduced the java.util.concurrent package, providing higher-level abstractions for thread coordination. Here's an updated version of the example:
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; 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(); } } }
This approach uses locks and conditions for improved thread coordination.
Consider the BlockingQueue Interface
If you require a blocking queue, consider using an implementation of the Java BlockingQueue interface, which provides a standard implementation with thread-safe and capacity-controlled operations.
The above is the detailed content of How Can Java's `wait()` and `notify()` Methods Be Used to Implement a Blocking Queue?. For more information, please follow other related articles on the PHP Chinese website!