用java的多线程知识写代码:生产面包,超过20个wait,没超过可以一直生产,每次生产5个。销售面包,等于0个wait,大于0个,可以一直卖,每次卖一个
时间: 2024-03-08 18:45:56 浏览: 18
好的,以下是Java多线程实现生产和销售面包的代码:
```
public class Bread {
private int count = 0;
public synchronized void produce() {
while (count >= 20) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count += 5;
System.out.println(Thread.currentThread().getName() + " 生产了5个面包,当前面包数量为:" + count);
notifyAll();
}
public synchronized void sell() {
while (count <= 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
System.out.println(Thread.currentThread().getName() + " 卖出了1个面包,当前面包数量为:" + count);
notifyAll();
}
}
```
在这个代码中,我们使用了一个共享变量count来表示当前面包的数量。在produce方法中,我们使用while循环来等待面包数量小于20。如果大于等于20,则调用wait方法进入等待状态。当面包数量小于20时,我们生产5个面包并打印出来,然后使用notifyAll方法唤醒其他等待中的线程。
在sell方法中,我们使用while循环来等待面包数量大于0。如果等于0,则调用wait方法进入等待状态。当面包数量大于0时,我们卖出1个面包并打印出来,然后使用notifyAll方法唤醒其他等待中的线程。
接下来,我们可以分别创建生产者和销售者线程,并启动它们:
```
public class Main {
public static void main(String[] args) {
Bread bread = new Bread();
for (int i = 1; i <= 3; i++) {
new Thread(() -> {
while (true) {
bread.produce();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "生产者" + i).start();
}
for (int i = 1; i <= 5; i++) {
new Thread(() -> {
while (true) {
bread.sell();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "销售者" + i).start();
}
}
}
```
在这个代码中,我们创建了3个生产者线程和5个销售者线程,并启动它们。生产者线程每隔1秒生产5个面包,销售者线程每隔0.5秒销售1个面包。由于我们使用了wait和notifyAll方法来控制线程的执行,因此生产和销售的过程会相互协调,保证面包数量不会超过20个或者小于0个。