zoukankan      html  css  js  c++  java
  • 多线程21:信号灯法

    解决方式2:
     
    并发协作模型"生产者/消费这模式"-->信号灯法
    • 来判断一个标志位flag,如果为true,就让他等待、如果为false,就让他去通知另外一个人、把两人衔接起来,就像咱们的信号灯红灯停,绿灯行,通过这样一个判断方式,只要来判断什么瑞后让他等待,什么时候将他唤醒就ok。
     1 package com.thread.gaoji;
     2 
     3 //测试生产者消费者问题2:信号灯法,通过标志位解决
     4 
     5 public class TestPC2 {
     6     public static void main(String[] args) {
     7         TV tv = new TV();
     8         new Player(tv).start();
     9         new Watcher(tv).start();
    10     }
    11 }
    12 
    13 //生产者-->演员
    14 class Player extends Thread {
    15     TV tv;
    16 
    17     public Player(TV tv) {
    18         this.tv = tv;
    19     }
    20 
    21     @Override
    22     public void run() {
    23         for (int i = 0; i < 20; i++) {
    24             if (i % 2 == 0) {
    25                 this.tv.play("快乐大本营播放中");
    26             } else {
    27                 this.tv.play("抖音:记录美好生活");
    28             }
    29         }
    30     }
    31 }
    32 
    33 //消费者-->观众
    34 class Watcher extends Thread {
    35     TV tv;
    36 
    37     public Watcher(TV tv) {
    38         this.tv = tv;
    39     }
    40 
    41     @Override
    42     public void run() {
    43         for (int i = 0; i < 20; i++) {
    44             tv.watch();
    45         }
    46     }
    47 }
    48 
    49 //产品-->节目
    50 class TV {
    51     //演员表演,观众等待 T
    52     //观众观看,演员等待 F
    53     String voice; // 表演的节目
    54     boolean flag = true;
    55 
    56 
    57     //表演
    58     public synchronized void play(String voice) {
    59 
    60         if (!flag) {
    61             try {
    62                 this.wait();
    63             } catch (InterruptedException e) {
    64                 e.printStackTrace();
    65             }
    66         }
    67         System.out.println("演员表演了:" + voice);
    68         //通知观众观看
    69         this.notifyAll();
    70         this.voice = voice;
    71         this.flag = !this.flag;
    72     }
    73 
    74     //观看
    75     public synchronized void watch() {
    76         if (flag) {
    77             try {
    78                 this.wait();
    79             } catch (InterruptedException e) {
    80                 e.printStackTrace();
    81             }
    82         }
    83         System.out.println("观看了:" + voice);
    84         //通知演员表演
    85         this.notifyAll();
    86         this.flag = !this.flag;
    87     }
    88 }

  • 相关阅读:
    每天一个JavaScript实例-铺货鼠标点击位置并将元素移动到该位置
    Max-Min Fairness带宽分配算法
    Centos Apache和tomcat集成配置,同一时候支持PHP和JAVA执行
    Linux硬件信息查询命令
    D3DXMatrixMultiply 函数
    垃圾回收GC:.Net自己主动内存管理 上(三)终结器
    使用python抓取CSDN关注人的全部公布的文章
    公司-科技:百度
    公司-科技:阿里巴巴
    公司-科技:腾讯
  • 原文地址:https://www.cnblogs.com/duanfu/p/12260812.html
Copyright © 2011-2022 走看看