在多线程编程中,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引入了一个并发库,提供了更高级别的抽象:
修改后的阻塞队列实现:
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中文网其他相关文章!