(3)编程实现生产者、消费者和共享数据区域,并编写测试代码验证。java
时间: 2024-03-08 14:46:50 浏览: 90
以下是使用Java语言实现的一个简单的生产者-消费者模型,其中包含共享数据区域和测试代码。
```java
import java.util.LinkedList;
import java.util.Queue;
// 共享数据区域,用于存储生产者生产的数据和消费者消费的数据
class SharedData {
private Queue<String> queue = new LinkedList<>();
private int maxSize = 5;
// 生产数据并加入共享数据区域
public synchronized void produce(String data) throws InterruptedException {
while (queue.size() == maxSize) {
System.out.println("SharedData: shared data area is full, waiting...");
wait();
}
queue.add(data);
System.out.println("SharedData: produce data " + data);
notifyAll();
}
// 消费数据并从共享数据区域中移除
public synchronized String consume() throws InterruptedException {
while (queue.isEmpty()) {
System.out.println("SharedData: shared data area is empty, waiting...");
wait();
}
String data = queue.poll();
System.out.println("SharedData: consume data " + data);
notifyAll();
return data;
}
}
// 生产者线程
class ProducerThread extends Thread {
private int id;
private SharedData sharedData;
public ProducerThread(int id, SharedData sharedData) {
this.id = id;
this.sharedData = sharedData;
}
@Override
public void run() {
try {
while (true) {
String data = "Data from producer " + id;
sharedData.produce(data);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 消费者线程
class ConsumerThread extends Thread {
private int id;
private SharedData sharedData;
public ConsumerThread(int id, SharedData sharedData) {
this.id = id;
this.sharedData = sharedData;
}
@Override
public void run() {
try {
while (true) {
String data = sharedData.consume();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 测试代码
public class ProducerConsumerTest {
public static void main(String[] args) {
SharedData sharedData = new SharedData();
// 创建生产者和消费者线程,并启动它们
ProducerThread[] producers = new ProducerThread[3];
ConsumerThread[] consumers = new ConsumerThread[3];
for (int i = 0; i < 3; i++) {
producers[i] = new ProducerThread(i, sharedData);
consumers[i] = new ConsumerThread(i, sharedData);
producers[i].start();
consumers[i].start();
}
// 等待所有线程结束
try {
for (int i = 0; i < 3; i++) {
producers[i].join();
consumers[i].join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
运行以上代码,可以看到生产者会不断地生产数据并加入共享数据区域,消费者会不断地从共享数据区域中取出数据进行消费,两者之间通过共享数据区域进行通信,从而实现了一个简单的生产者-消费者模型。
阅读全文