用Java编程实现生产者-消费者模型
时间: 2023-11-04 22:04:40 浏览: 94
好的,关于生产者-消费者模型的实现,可以使用Java中的阻塞队列来实现。具体实现方式可以参考以下代码:
```java
import java.util.concurrent.ArrayBlockingQueue;
public class ProducerConsumer {
private static final int BUFFER_SIZE = 10;
private static ArrayBlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(BUFFER_SIZE);
public static void main(String[] args) {
Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());
producerThread.start();
consumerThread.start();
}
static class Producer implements Runnable {
@Override
public void run() {
try {
int i = 1;
while (true) {
buffer.put(i);
System.out.println("Producer produced " + i);
i++;
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Consumer implements Runnable {
@Override
public void run() {
try {
while (true) {
int num = buffer.take();
System.out.println("Consumer consumed " + num);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这段代码中使用了一个ArrayBlockingQueue作为生产者和消费者之间的缓冲区。生产者不断往缓冲区中放入数据,消费者则从缓冲区中取出数据进行处理。如果缓冲区已满,则生产者会被阻塞;如果缓冲区已空,则消费者会被阻塞。这样可以保证生产者和消费者之间的同步。
阅读全文