黑马程序员
等待唤醒机制分析
案例
- 包子铺
- 吃货
- 主方法
package baoZiPuDemo;
public class BaoZi {
String pi;
String xian;
boolean flag=false;
}
package baoZiPuDemo;
public class BaoZiPu extends Thread {
private BaoZi baoZi;
public BaoZiPu(BaoZi baoZi) {
this.baoZi = baoZi;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (baoZi) {
if (baoZi.flag) {
try {
baoZi.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count % 2 == 0) {
baoZi.pi="薄皮";
baoZi.xian="三鲜";
}else {
baoZi.pi="冰皮";
baoZi.xian="羊肉";
}
count++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
baoZi.flag=true;
baoZi.notify();
System.out.println(baoZi.pi+baoZi.xian+"已准备就绪");
}
}
}
}
package baoZiPuDemo;
public class ChiHuo extends Thread {
private BaoZi baoZi;
public ChiHuo(BaoZi baoZi) {
this.baoZi = baoZi;
}
@Override
public void run() {
while (true) {
synchronized (baoZi) {
if (!baoZi.flag) {
try {
baoZi.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("顾客正在吃"+baoZi.pi+baoZi.xian);
baoZi.flag=false;
baoZi.notify();//控制包子铺
System.out.println(baoZi.pi+baoZi.xian+"已吃完\n*****************");
}
}
}
}
package baoZiPuDemo;
public class DemoTest {
public static void main(String[] args) {
BaoZi baoZi=new BaoZi();
new BaoZiPu(baoZi).start();
new ChiHuo(baoZi).start();
}
}