生产者消费者Java实现
时间: 2023-11-13 21:20:17 浏览: 88
生产者消费者问题是一个经典的并发编程问题,可以用Java中的多线程机制来实现。
下面是一个简单的Java实现示例:
```java
import java.util.LinkedList;
public class ProducerConsumer {
public static void main(String[] args) {
LinkedList<Integer> queue = new LinkedList<>();
int maxSize = 5;
Thread producer = new Thread(new Producer(queue, maxSize), "Producer");
Thread consumer = new Thread(new Consumer(queue), "Consumer");
producer.start();
consumer.start();
}
}
class Producer implements Runnable {
private final LinkedList<Integer> queue;
private final int maxSize;
public Producer(LinkedList<Integer> queue, int maxSize) {
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == maxSize) {
try {
System.out.println("Queue is full, Producer thread is waiting for consumer to consume items...");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int num = (int) (Math.random() * 100);
queue.add(num);
System.out.println("Produced item: " + num);
queue.notifyAll();
}
}
}
}
class Consumer implements Runnable {
private final LinkedList<Integer> queue;
public Consumer(LinkedList<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
System.out.println("Queue is empty, Consumer thread is waiting for producer to produce items...");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int num = queue.removeFirst();
System.out.println("Consumed item: " + num);
queue.notifyAll();
}
}
}
}
```
这个示例中,有一个生产者线程和一个消费者线程,它们共享一个队列。生产者线程会不断地往队列中添加随机数,如果队列已满,则等待消费者线程消费后再继续生产。消费者线程会不断地从队列中取出数字并输出,如果队列为空,则等待生产者线程生产后再继续消费。
需要注意的是,在访问共享资源(也就是队列)时要使用`synchronized`关键字进行同步,同时使用`wait()`和`notifyAll()`方法进行线程间通信,以保证线程安全和正确性。
阅读全文