线程:生产者消费者模式(信号灯法)

 1 /**
 2  * 线程并发协作
 3  * 生产者消费者模式
 4  * 信号灯法(借助标志位)
 5  * 模拟电视演员观众
 6  * 只有生产者生产了,消费者才能使用,否则无法使用
 7  * 
 8  * 代码构造:生产者(表演者)、消费者(观看者)、电视
 9  */
10 public class XinHaoDeng {
11     public static void main(String[] args) {
12         TV tv = new TV();
13         new Performer(tv).start();
14         new Watcher(tv).start();
15     }
16 }
17 
18 //生产者(表演者)
19 class Performer extends Thread{
20     TV tv ;
21     public Performer(TV tv) {
22         this.tv = tv;
23     }
24     @Override
25     public void run() {
26         for(int i=0;i<100;i++) {
27             if(i%2 ==0) {
28                 this.tv.perform("胸口碎大石!");
29             }else {
30                 this.tv.perform("巴啦啦能量!呜呼哀哉!仙王归位!");
31             }
32         }
33     }
34 }
35 //消费者(观看者)
36 class Watcher extends Thread{
37     TV tv ;
38     public Watcher(TV tv) {
39         this.tv = tv;
40     }
41     @Override
42     public void run() {
43         for(int i=0;i<100;i++) {
44             tv.watch();
45         }
46     }
47 }
48 //信号灯(标志位)
49 class TV{
50     private String say;    //数据对象
51     private boolean flag = true; //信号灯(标志位),true是表演者表演,false是观看者观看
52     //表演
53     public synchronized void perform(String say) {
54         if(!flag) {
55             try {
56                 this.wait();
57             } catch (InterruptedException e) {
58                 e.printStackTrace();
59             }
60         }
61         System.out.println("表演了:"+say);
62         this.say = say;
63         this.notifyAll();
64         this.flag = !flag;
65     }
66     
67     //观看
68     public synchronized void watch() {
69         if(flag) {
70             try {
71                 this.wait();
72             } catch (InterruptedException e) {
73                 e.printStackTrace();
74             }
75         }
76         System.out.println("观看了:"+say);
77         this.notifyAll();
78         this.flag = !flag;
79     }
80 }

结果:

  表演了:胸口碎大石!
  观看了:胸口碎大石!
  表演了:巴啦啦能量!呜呼哀哉!仙王归位!
  观看了:巴啦啦能量!呜呼哀哉!仙王归位!
  表演了:胸口碎大石!
  观看了:胸口碎大石!
  表演了:巴啦啦能量!呜呼哀哉!仙王归位!
  观看了:巴啦啦能量!呜呼哀哉!仙王归位!
  表演了:胸口碎大石!
  观看了:胸口碎大石!
  表演了:巴啦啦能量!呜呼哀哉!仙王归位!
  观看了:巴啦啦能量!呜呼哀哉!仙王归位!
  表演了:胸口碎大石!
  观看了:胸口碎大石!
  表演了:巴啦啦能量!呜呼哀哉!仙王归位!
  观看了:巴啦啦能量!呜呼哀哉!仙王归位!

posted @ 2020-07-14 21:01  梅竹疯狂打豆豆  阅读(193)  评论(0)    收藏  举报