使用java模拟生产者和消费者问题
时间: 2024-05-05 08:16:31 浏览: 107
生产者和消费者问题是一个经典的并发编程问题,可以使用Java语言来模拟实现。下面是一个使用Java多线程实现生产者和消费者问题的示例代码:
```java
import java.util.LinkedList;
import java.util.Queue;
public class ProducerConsumer {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
int maxSize = 10;
Thread producerThread = new Thread(new Producer(queue, maxSize), "Producer");
Thread consumerThread = new Thread(new Consumer(queue), "Consumer");
producerThread.start();
consumerThread.start();
}
static class Producer implements Runnable {
private Queue<Integer> queue;
private int maxSize;
public Producer(Queue<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, waiting for consumer to consume...");
queue.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
int number = (int) (Math.random() * 100);
queue.add(number);
System.out.println("Produced " + number);
queue.notifyAll();
}
}
}
}
static class Consumer implements Runnable {
private Queue<Integer> queue;
public Consumer(Queue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
System.out.println("Queue is empty, waiting for producer to produce...");
queue.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
int number = queue.remove();
System.out.println("Consumed " + number);
queue.notifyAll();
}
}
}
}
}
```
上面的代码中,生产者线程和消费者线程都是使用`Runnable`接口实现的,并且都使用`synchronized`关键字来保证线程安全。生产者线程在队列满时等待,消费者线程在队列空时等待,当有新的元素加入队列时,生产者线程会唤醒等待的消费者线程,当有元素被消费时,消费者线程会唤醒等待的生产者线程。这种实现方式可以有效避免死锁和饥饿等并发编程问题。
阅读全文