Java 11 编程实现生产者、消费者和共享数据区域,并编写测试代码验证。
时间: 2024-03-08 18:46:20 浏览: 97
生产者消费者java实现
5星 · 资源好评率100%
以下是Java 11实现生产者、消费者和共享数据区域的示例代码:
```java
import java.util.LinkedList;
public class SharedData {
private LinkedList<Integer> buffer = new LinkedList<>();
private int maxSize;
public SharedData(int maxSize) {
this.maxSize = maxSize;
}
public synchronized void produce(int num) {
while (buffer.size() == maxSize) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer.add(num);
System.out.println("Produced: " + num);
notify();
}
public synchronized int consume() {
while (buffer.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int num = buffer.removeFirst();
System.out.println("Consumed: " + num);
notify();
return num;
}
}
public class Producer implements Runnable {
private SharedData sharedData;
private int num;
public Producer(SharedData sharedData, int num) {
this.sharedData = sharedData;
this.num = num;
}
@Override
public void run() {
sharedData.produce(num);
}
}
public class Consumer implements Runnable {
private SharedData sharedData;
public Consumer(SharedData sharedData) {
this.sharedData = sharedData;
}
@Override
public void run() {
sharedData.consume();
}
}
public class Test {
public static void main(String[] args) {
SharedData sharedData = new SharedData(5);
Thread producer1 = new Thread(new Producer(sharedData, 1));
Thread producer2 = new Thread(new Producer(sharedData, 2));
Thread consumer1 = new Thread(new Consumer(sharedData));
Thread consumer2 = new Thread(new Consumer(sharedData));
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
}
}
```
测试代码如下:
```java
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class TestSharedData {
@Test
void testSharedData() {
SharedData sharedData = new SharedData(5);
Thread producer1 = new Thread(new Producer(sharedData, 1));
Thread producer2 = new Thread(new Producer(sharedData, 2));
Thread consumer1 = new Thread(new Consumer(sharedData));
Thread consumer2 = new Thread(new Consumer(sharedData));
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
try {
producer1.join();
producer2.join();
consumer1.join();
consumer2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(sharedData.consume(), 1);
assertEquals(sharedData.consume(), 2);
}
}
```
该测试代码创建了一个包含5个元素的共享数据区域,并创建了两个生产者和两个消费者线程。测试代码验证了生产者是否能够正确地将元素添加到共享数据区域中,消费者是否能够正确地从共享数据区域中取出元素。
阅读全文