使用java实现 生产者-消费者(仓库)程序
时间: 2024-01-24 18:03:56 浏览: 26
好的,以下是使用Java实现生产者-消费者(仓库)程序的代码:
```java
import java.util.LinkedList;
public class ProducerConsumerExample {
public static void main(String[] args) {
final PC pc = new PC();
// 创建生产者线程
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 创建消费者线程
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 启动线程
t1.start();
t2.start();
// 等待线程结束
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 仓库类
public static class PC {
// 仓库大小
private final int CAPACITY = 10;
// 用于存放产品的仓库
private final LinkedList<Integer> queue = new LinkedList<>();
// 生产者
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (this) {
// 如果仓库已满,则等待
while (queue.size() == CAPACITY) {
wait();
}
System.out.println("生产者生产: " + value);
// 生产产品并放入仓库
queue.add(value++);
// 唤醒消费者线程
notify();
// 休眠一段时间
Thread.sleep(1000);
}
}
}
// 消费者
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
// 如果仓库为空,则等待
while (queue.size() == 0) {
wait();
}
// 从仓库中取出产品
int value = queue.removeFirst();
System.out.println("消费者消费: " + value);
// 唤醒生产者线程
notify();
// 休眠一段时间
Thread.sleep(1000);
}
}
}
}
}
```
在上面的代码中,我们使用了一个`LinkedList`来模拟仓库,其中`CAPACITY`表示仓库的大小,`queue`表示存放产品的队列。`produce()`方法用于生产产品,`consume()`方法用于消费产品。在生产和消费产品时,我们使用`synchronized`来保证线程同步,使用`wait()`和`notify()`来控制线程的运行。在生产产品时,如果仓库已满,则生产者线程将等待;在消费产品时,如果仓库为空,则消费者线程将等待。这样就实现了生产者-消费者(仓库)程序。