编程实现生产者、消费者和共享数据区域,并编写测试代码验证。给出java代码
时间: 2024-03-08 08:46:34 浏览: 103
以下是一个简单的Java代码实现生产者、消费者和共享数据区域的例子,并包含测试代码:
```java
import java.util.LinkedList;
public class ProducerConsumerExample {
public static void main(String[] args) {
SharedData sharedData = new SharedData();
Thread producer = new Thread(new Producer(sharedData));
Thread consumer = new Thread(new Consumer(sharedData));
producer.start();
consumer.start();
}
static class SharedData {
private final LinkedList<Integer> buffer = new LinkedList<>();
private final int MAX_SIZE = 10;
public synchronized void produce(int i) {
while (buffer.size() == MAX_SIZE) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer.add(i);
System.out.println("Produced: " + i);
notify();
}
public synchronized int consume() {
while (buffer.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int i = buffer.remove();
System.out.println("Consumed: " + i);
notify();
return i;
}
}
static class Producer implements Runnable {
private final SharedData sharedData;
public Producer(SharedData sharedData) {
this.sharedData = sharedData;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
sharedData.produce(i);
try {
Thread.sleep((long) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable {
private final SharedData sharedData;
public Consumer(SharedData sharedData) {
this.sharedData = sharedData;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
sharedData.consume();
try {
Thread.sleep((long) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
```
测试代码:
```java
@Test
public void testProducerConsumer() {
ProducerConsumerExample.SharedData sharedData = new ProducerConsumerExample.SharedData();
Thread producer = new Thread(new ProducerConsumerExample.Producer(sharedData));
Thread consumer = new Thread(new ProducerConsumerExample.Consumer(sharedData));
producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
```
阅读全文