多线程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 }

 

posted @ 2020-02-04 19:54  断浮  阅读(737)  评论(0编辑  收藏  举报