需求分析:
包子类:皮、馅、是否有货。
包子铺:有个锁对象(包子)、先判断包子是否有货(flag是否等于false)
若有货-》包子铺调用wait()进入休息状态
若无货-》包子铺开始做包子-》做好包子修改包子的flag为true并调用notify()唤醒顾客线程
顾客:有个锁对象(包子)、先判断还有没有包子(flag是否等于true)
若有货-》顾客开始吃包子,吃完包子后将flag设置为false并调用notify()唤醒包子铺开始做包子
若无货-》则调用wait()
具体代码如下:
包子类:
public class BaoZi {
public String Pi;
public String Xian;
public boolean flag;
}
包子铺类:
import java.util.Random;
public class BaoZiPu extends Thread {
private BaoZi bz;
public BaoZiPu(BaoZi bz){
this.bz = bz;
}
@Override
public void run() {
String pis[]={"玉米皮","小麦皮","大豆皮","无皮"};
String xians[]={"西葫芦","虾米","韭菜","猪肉大葱"};
int i=0,j=0;
while (true){
synchronized (bz){
if (bz.flag){
try {
bz.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i = (int) (Math.random()*10000)%pis.length;
j = (int) (Math.random()*10000)%xians.length;
bz.Pi=pis[i];
bz.Xian=xians[j];
System.out.println(i+","+j+"正在做"+bz.Pi+bz.Xian+"馅的包子");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bz.flag=true;
bz.notify();
}
}
}
}
顾客类:
public class Customer extends Thread {
private BaoZi bz;
public Customer(BaoZi bz){
this.bz = bz;
}
@Override
public void run() {
while (true){
synchronized (bz){
if (!bz.flag){
try {
bz.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("顾客正在吃"+bz.Pi+bz.Xian+"馅的包子");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bz.flag=false;
bz.notify();
System.out.println("顾客已经吃完"+bz.Pi+bz.Xian+"馅的包子,包子铺正在做包子");
}
}
}
}
最后运行结果图:
来源:CSDN
作者:zg97zb
链接:https://blog.csdn.net/zg97zb/article/details/103757157