JAVA单排日记-2020/1/20-等待与唤醒机制

1.线程之间的通信

  • 概念:多个线程处理同一个资源,但是处理动作(线程任务)却不同,通信(等待唤醒机制)可以避免多个线程对同一个共享变量争夺
  • 例子:
    在这里插入图片描述

2.代码实现

在这里插入图片描述

public class Demo03 {
    public static void main(String[] args) {
        BaoZi baoZi = new BaoZi(false, "小笼包");

        new Thread() {
            @Override
            public void run() {
                while (true) {//循环,顾客一直吃包子
                    synchronized (baoZi) {//顾客吃包子,老板做包子不能同时进行,使用同步锁
                        if (!baoZi.isNum()) {//如果包子没有,唤醒老板做包子
                            System.out.println("顾客:老板,来一屉小笼包");
                            baoZi.notify();//唤醒老板线程
                        }
                        try {//顾客线程进入等待
                            baoZi.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("谢谢老板,小笼包开吃了");//被唤醒后顾客开始吃包子,包子状态改为false
                        System.out.println("=================================");
                        baoZi.setNum(false);
                    }
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                while (true) {//循环,老板一直卖包子
                    synchronized (baoZi) {//如果包子有,老板进入等待
                        if (baoZi.isNum()) {
                            try {
                                baoZi.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        //包子没有,老板被顾客唤醒,开始做包子
                        System.out.println("开始做包子,等5s");
                        try {
                            sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("包子做好了,吃吧");
                        baoZi.setNum(true);//做完包子后包子设置为true,并且唤醒顾客吃包子
                        baoZi.notify();
                    }
                }
            }
        }.start();
    }
}

在这里插入图片描述

发布了90 篇原创文章 · 获赞 1 · 访问量 2041

猜你喜欢

转载自blog.csdn.net/wangzilong1995/article/details/104054633