用Java实现编程实现生产者、消费者和共享数据区域,并编写测试代码验证
时间: 2024-03-06 11:50:54 浏览: 62
好的,以下是Java实现生产者、消费者和共享数据区域的代码:
```java
public class SharedData {
private int data;
private boolean available = false;
public synchronized void setData(int data) {
while (available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data = data;
available = true;
notifyAll();
}
public synchronized int getData() {
while (!available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
available = false;
notifyAll();
return data;
}
}
public class Producer implements Runnable {
private SharedData sharedData;
public Producer(SharedData sharedData) {
this.sharedData = sharedData;
}
public void run() {
for (int i = 0; i < 5; i++) {
sharedData.setData(i);
System.out.println("Producer produced: " + i);
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Consumer implements Runnable {
private SharedData sharedData;
public Consumer(SharedData sharedData) {
this.sharedData = sharedData;
}
public void run() {
for (int i = 0; i < 5; i++) {
int data = sharedData.getData();
System.out.println("Consumer consumed: " + data);
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
SharedData sharedData = new SharedData();
Producer producer = new Producer(sharedData);
Consumer consumer = new Consumer(sharedData);
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}
```
以上代码中,`SharedData` 类表示共享数据区域,其中 `setData()` 和 `getData()` 方法分别用于设置数据和获取数据,并且使用 `synchronized` 关键字保证了线程安全。`Producer` 类表示生产者,其中 `run()` 方法循环生产数据,并将数据设置到共享数据区域中。`Consumer` 类表示消费者,其中 `run()` 方法循环消费数据,并从共享数据区域中获取数据。`ProducerConsumerTest` 类用于测试生产者和消费者的运行效果。
运行测试代码后,可以看到生产者和消费者交替运行,生产者生产数据并设置到共享数据区域中,消费者从共享数据区域中获取数据并消费。生产者和消费者通过共享数据区域进行通信,从而实现了线程间的协作。
阅读全文