等待唤醒案例:线程之间的通信
创建一个顾客线程(消费者):告知老板要的包子的种类和数量,调用wait方法,放弃cpu执行,进入waiting状态(无限等待)
创建一个老板线程(生产者):花了5秒做包子,做好了包子之后,调用notify方法,唤醒顾客吃包子
注意事项:
顾客和老板线程必须使用同步代码块包裹起来,保证等待和唤醒只能有一个在执行
同步使用的锁对象是唯一的
只有锁对象才能调用wait和notify方法
import java.util.Objects; public class Demo01waitAndNotify { public static void main(String[] args) { Object obj=new Object(); new Thread(){ @Override public void run() { while (true){ synchronized (obj){ System.out.println("告知老板要的包子的种类和数量"); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("包子已经做好了开吃"); } } } }.start(); new Thread(){ @Override public void run() { while (true){ try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj){ System.out.println("老板5秒之后做好包子告诉顾客可以吃包子"); obj.notify(); } } } }.start(); } }