- package com.fgy.demo05;
- /**
- * 等待唤醒案例: 线程之间通信
- * 注意:
- * 同步使用的锁对象必须唯一
- * 只有锁对象才能调用 wait 和 notify()/notifyAll() 方法
- */
- public class Demo1WaitAndNotify {
- public static void main(String[] args) {
- Object obj = new Object();
- new Thread() {
- @Override
- public void run() {
- synchronized (obj) {
- System.out.println("顾客告知要的包子和数量");
- try {
- obj.wait();
- // obj.wait(5000); // 如果 5 秒后没有被唤醒, 则会自动醒来
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("老板把包子做好了, 可以开吃");
- }
- }
- }.start();
- new Thread() {
- @Override
- public void run() {
- try {
- Thread.sleep(5000); // 花费 5 秒做包子
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized (obj) {
- System.out.println("告知客户, 可以吃包子了");
- obj.notify();
- }
- }
- }.start();
- }
- }
来源: http://www.bubuko.com/infodetail-3352070.html