等待唤醒机制
线程之间的通信:多个线程在处理同一个资源,但是处理的动作(线程的任务)却不相同。通过一定的手段使各个线程能有效的利用资源。而这种手段即—— 等待唤醒机制。
等待唤醒机制所涉及到的方法:
1、wait() :等待,将正在执行的线程释放其执行资格 和 执行权,并存储到线程池中。
2、notify():唤醒,唤醒线程池中被wait()的线程,一次唤醒一个,而且是任意的。
3、notifyAll(): 唤醒全部:可以将线程池中的所有wait() 线程都唤醒。
//资源类
public class BaoZi {
boolean flag=false;
String pi;
String xian;
}
//生产类
public class BaoZiPu implements Runnable {
private BaoZi bz;
public BaoZiPu(BaoZi bz) {
this.bz = bz;
}
@Override
public void run() {
int count = 0;
while(true){
synchronized (bz) {
if (bz.flag==true ) {
try {
bz.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (bz.flag==false){
if (count % 2 == 0) {
bz.pi = "薄皮";
bz.xian = "三鲜";
}
if(count%2==1)
{
bz.xian="冰皮";
bz.pi="猪肉大葱";
}
System.out.println("正在生产"+bz.pi+bz.xian+"包子");
try {
Thread.sleep(3000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
bz.flag = true;
bz.notify();
System.out.println("包子铺已经生产好了:"+bz.pi+bz.xian+"吃货可以开始吃了");
System.out.println("===================");
}
}
count++;
}
}
}
//消费类
public class ChiHuo implements Runnable {
private BaoZi bz;
public ChiHuo(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("吃货开始吃包子");
bz.flag = false;
System.out.println("吃货已经把包子吃完了");
System.out.println("包子铺可以开始生产包子");
System.out.println("============");
bz.notify();
}
}
}
}
//测试类
public class WaitAndNotify {
public static void main(String[] args) {
BaoZi bz=new BaoZi();
BaoZiPu baoZiPu=new BaoZiPu(bz);
ChiHuo chiHuo=new ChiHuo(bz);
new Thread(baoZiPu).start();
new Thread(chiHuo).start();
}
}