zoukankan      html  css  js  c++  java
  • 线程间通信简单概念

    如果说多个线程间,不仅仅只涉及到对同一个资源的竞争,而是还存在对同一个资源的协作,类似于生产者-消费者模式,这个时候就设计到线程间通信,我们可以通过等待唤醒机制来实现。

    情景再现

    我们去早餐店吃包子,包子是我们共同的目标,老板卖包子我们买包子。这就是生产者-消费模式

    包子类:

    public class Baozi {
        private String name;
        boolean flag = false;//包子是否准备好
    
        public Baozi(String name) {
            this.name = name;
        }
    }

    消费者类:

    public class Customer extends Thread {
    
        private Baozi baozi;
    
        public Customer(String name, Baozi baozi) {
            super(name);
            this.baozi = baozi;
        }
    
        @Override
        public void run() {
            while (true){
                synchronized (baozi){
                    if (baozi.flag == false){//包子还没有做好 等待
                        try {
                            System.out.println(getName()+ ":  包子还没做好,老板快点");
                            baozi.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
    
                    System.out.println(getName()+":  包子已经做好了,开吃");
                    baozi.flag = false;
                    baozi.notify();//吆喝一声 包子吃完了
                }
            }
        }
    
    
    }

    生产者类:

    public class Producer extends Thread{
    
        private Baozi baozi;
    
        public Producer(String name, Baozi baozi) {
            super(name);
            this.baozi = baozi;
        }
    
        @Override
        public void run() {
            while (true){
                synchronized (baozi){
                    if (baozi.flag){//包子准备好了,我先休息一下
                        try {
                            baozi.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
    
                    System.out.println(getName()+":  包子没做好,赶紧做");
                    baozi.flag = true;
                    System.out.println(getName()+":  包子做好了,大家来吃吧");
                    baozi.notify();
                }
    
            }
        }
    }
    public static void main(String[] args) {
    
            Baozi baozi = new Baozi("鲜肉大包子");
            Customer customer = new Customer("顾客",baozi);
            Producer producer = new Producer("老板",baozi);
    
            producer.start();
            customer.start();
    
        }

    运行结果:

    运行结果如预期,生产者线程负责生产,消费者线程负责消费,分工明确,有条不絮。你耕田来我织布

  • 相关阅读:
    routing路由模式
    MQ的订阅模式
    RabbitMq中的消息应答与持久化
    work工作消息队列Round-robin与Fair dispatch
    040 关于hive元数据的解析
    simple简单消息队列
    用户设置与virtual host配置
    Mq的介绍
    字典
    元组Tuple
  • 原文地址:https://www.cnblogs.com/zhvip/p/12696836.html
Copyright © 2011-2022 走看看