线程实现顾客买包子
作者:互联网
//需求:利用线程的等待唤醒机制实现包子铺生产包子,吃货消费包子 // 具体:顾客要包子,老板做包子,顾客等待 // 老板3秒做好,老板等待,顾客4秒吃完, // 顾客吃完继续要包子,老板做包子,顾客等待 // …… // 实现:三个类,老板顾客类,两个线程,异步共享包子这个数据源; // 包子类,顾客或者老板依据包子的有无做出行为, // 有包子,顾客吃,老板等待 // 没有包子,老板做包子,顾客等
//测试类
public class T {
public static void main(String[] args) {
BAOZI bz=new BAOZI();
new LAOBAN(bz).start();
new GUKE(bz).start();
}
}
//包子类
public class BAOZI {
boolean flag=false;
}
//老板类
public class LAOBAN extends Thread{
private BAOZI bz;
public LAOBAN(BAOZI bz){
this.bz=bz;
}
@Override
public void run() {
while (true){
synchronized (bz){
if (bz.flag==true){
try {
bz.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//等待2秒开始做包子
System.out.println("没有包子,老板准备做包子(2s)");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("老板正在做包子(5s)");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bz.flag=true;
System.out.println("包子做好,给顾客吃");
bz.notify();
}
}
}
}
//顾客类
public class GUKE extends Thread{
private BAOZI bz;
public GUKE(BAOZI bz){
this.bz=bz;
}
@Override
public void run() {
while (true){
synchronized (bz){
if (bz.flag==false){
try {
bz.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("顾客开始吃包子(3s)");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bz.flag=false;
System.out.println("顾客吃完包子");
bz.notify();
System.out.println("------------------");
}
}
}
}
标签:public,BAOZI,线程,老板,顾客,包子,bz 来源: https://blog.csdn.net/mn766525/article/details/122609354