- public class Cooking {
- boolean hasSalut = false;
- Object object = new Object();
- public void cook() {
- if (!hasSalut) {
- System.out.println("做饭没盐了,快去买盐");
- new Thread(new Son()).start();
- synchronized (object) {
- try {
- object.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- System.out.println("有盐了,开始做饭~");
- }
-
- }
- class Son implements Runnable {
- @Override
- public void run() {
- System.out.println("麻麻,我去买盐了~~");
-
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized (object) {
- System.out.println("麻麻,买到了~~");
- object.notify();
- }
- }
- }
-
- public static void main(String[] args) {
- Cooking cooking = new Cooking();
- cooking.cook();
- }
- }
复制代码 |