生产者-消费者问题(计算机系统中的许多问题都可归结为此问题)描述如下:生产者与消费者可以通过一个环形缓冲池联系起来,环形缓冲池由几个大小相等的缓冲块组成,每个缓冲块容纳一个产品。每个生产者可不断地每次往缓冲池中送一个生产产品,而每个消费者则可不断地每次从缓冲池中取出一个产品。 编写程序模拟多个生产者和多个消费者共享缓冲池的生产和消费过程。 要求: 1. 设计信号量用于进行生产者-消费者、生产者-生产者、消费者-消费者之间的同步控制; 2. 创建多个(不少于5个)进程或者线程模拟生产者和消费者; 3. 缓冲池大小定义在10-20,缓冲块中的产品为数据; 4. 程序运行结果能实时显示缓冲池中生产和消费产品的过程,包括断点、推进时间、次序等,编程语言选用Java。
时间: 2024-02-13 21:04:49 浏览: 13
好的,这是一个经典的并发编程问题。以下是我的解决方案:
首先,我们需要定义一个环形缓冲池类,用于存储产品和实现生产者-消费者之间的同步控制:
```java
public class CircularBuffer {
private int[] buffer;
private int size;
private int writePointer;
private int readPointer;
private Semaphore empty;
private Semaphore full;
private Semaphore mutex;
public CircularBuffer(int size) {
this.size = size;
buffer = new int[size];
writePointer = 0;
readPointer = 0;
empty = new Semaphore(size);
full = new Semaphore(0);
mutex = new Semaphore(1);
}
public void produce(int data) throws InterruptedException {
empty.acquire();
mutex.acquire();
buffer[writePointer] = data;
System.out.println("Producer " + Thread.currentThread().getId() + " produced " + data + " at " + writePointer);
writePointer = (writePointer + 1) % size;
mutex.release();
full.release();
}
public int consume() throws InterruptedException {
full.acquire();
mutex.acquire();
int data = buffer[readPointer];
System.out.println("Consumer " + Thread.currentThread().getId() + " consumed " + data + " at " + readPointer);
readPointer = (readPointer + 1) % size;
mutex.release();
empty.release();
return data;
}
}
```
其中,`empty`表示缓冲池中空缓冲块的数量,`full`表示缓冲池中满缓冲块的数量,`mutex`用于实现互斥访问缓冲池。`produce`方法用于生产产品,`consume`方法用于消费产品。
接下来,我们需要创建多个生产者和消费者线程,并模拟生产和消费过程:
```java
public class ProducerConsumer {
public static void main(String[] args) {
CircularBuffer buffer = new CircularBuffer(10);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
try {
while (true) {
int data = (int) (Math.random() * 100);
buffer.produce(data);
Thread.sleep((int) (Math.random() * 100));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
for (int i = 0; i < 5; i++) {
new Thread(() -> {
try {
while (true) {
int data = buffer.consume();
Thread.sleep((int) (Math.random() * 100));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
}
```
在程序运行时,可以看到生产者和消费者交替地访问缓冲池,实现了并发生产和消费:
```
Producer 10 produced 71 at 0
Consumer 11 consumed 71 at 0
Producer 12 produced 24 at 1
Consumer 10 consumed 24 at 1
Producer 10 produced 55 at 2
Consumer 12 consumed 55 at 2
Producer 11 produced 85 at 3
Consumer 11 consumed 85 at 3
Producer 12 produced 20 at 4
Consumer 10 consumed 20 at 4
Producer 11 produced 8 at 5
Consumer 12 consumed 8 at 5
...
```
以上就是我的解决方案,希望可以帮到你。
阅读全文