Java实现生产者-消费者
时间: 2023-07-18 14:41:40 浏览: 63
生产者-消费者是一个经典的多线程编程问题,Java提供了多种实现方式,下面给出一种基于wait()和notify()方法的实现:
```
public class ProducerConsumer {
private List<Integer> buffer = new ArrayList<>();
private int maxSize = 5;
public void produce() throws InterruptedException {
synchronized (this) {
while (buffer.size() == maxSize) {
wait();
}
Random random = new Random();
int number = random.nextInt(100);
buffer.add(number);
System.out.println("生产者生产了:" + number);
notifyAll();
}
}
public void consume() throws InterruptedException {
synchronized (this) {
while (buffer.size() == 0) {
wait();
}
int number = buffer.remove(0);
System.out.println("消费者消费了:" + number);
notifyAll();
}
}
}
```
在这个例子中,生产者和消费者共享一个缓冲区,当缓冲区满时,生产者会调用wait()方法等待,当缓冲区为空时,消费者会调用wait()方法等待。当生产者生产一个数据时,会调用notifyAll()方法通知所有等待的线程,消费者消费一个数据时也会调用notifyAll()方法通知所有等待的线程。需要注意的是,wait()和notify()方法必须在同步代码块内调用,否则会抛出IllegalMonitorStateException异常。