/**
* @author Administrator
* @version 1.0
* @description: 包子铺
* @date 2021/8/23 9:47
*/
public class Bzp {
static boolean flag = false;
public static void main(String[] args) {
//创建个线程池来执行这两个线程
ExecutorService es = Executors.newFixedThreadPool(2);
Bzp bzp1 = new Bzp();
//有包子
Runnable bzp = new Runnable() {
@Override
public void run() {
while (true) {
synchronized (bzp1) {
//包子铺类
if (flag==true) {
System.out.println("有包子");
try {
bzp1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//没有包子,开始做包子
System.out.println("开始做包子");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子做好了,开始吃");
flag = true;
bzp1.notify();
System.out.println("----------------------");
}
}
}
}
};
Runnable chiHuo = new Runnable() {
@Override
public void run() {
while (true) {
synchronized (bzp1) {
if (flag == false) {
//没有包子
System.out.println("没有包子开始包包子");
try {
bzp1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//有包子
System.out.println("有包子,吃包子");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子吃完了");
System.out.println("------------------");
flag = false;
bzp1.notify();
}
}
}
}
};
es.submit(bzp);
es.submit(chiHuo);
}
}