1 package cn.ftf.threadcooperation;
2 /**
3 * 生产者消费者模式实现方式之“信号灯法”---借助flag标志位
4 * 模拟表演者和观看者,表演了才能观看
5 * @author 房廷飞
6 *
7 */
8 public class CoTest02 {
9 public static void main(String[] args) {
10 Tv tv=new Tv();
11 Player pl=new Player(tv);
12 Watcher wa=new Watcher(tv);
13 pl.start();
14 wa.start();
15 }
16 }
17
18
19 class Tv{
20 String voice;
21 //T表示演员表演,观众等待
22 //F表示观众观看,演员等待
23 boolean flag=true;
24
25 //表演
26 public synchronized void play(String voice) {
27 //演员等待
28 if(!flag) {
29 try {
30 this.wait();
31 } catch (InterruptedException e) {
32 // TODO Auto-generated catch block
33 e.printStackTrace();
34 }if(!flag) {
35 try {
36 this.wait();
37 } catch (InterruptedException e) {
38 // TODO Auto-generated catch block
39 e.printStackTrace();
40 }
41 }
42 }
43 //表演时刻
44 System.out.println("表演了"+voice);
45 this.voice=voice;
46 //表演完毕,唤醒所有线程
47 this.notifyAll();
48 //切换灯
49 this.flag=!this.flag;
50 }
51
52 //观看
53 public synchronized void watch() {
54 //观众等待
55 if(flag) {
56 try {
57 this.wait();
58 } catch (InterruptedException e) {
59 // TODO Auto-generated catch block
60 e.printStackTrace();
61 }
62
63 }
64 System.out.println("观看了"+voice);
65 //观看完毕,唤醒所有线程
66 this.notifyAll();
67 //换灯
68 this.flag=!this.flag;
69 }
70 }
71
72
73 class Player extends Thread{
74 Tv tv;
75 public Player(Tv tv) {
76 super();
77 this.tv = tv;
78 }
79 public void run(){
80 for (int i=0;i<20;i++) {
81 if(i%2==0) {
82 this.tv.play(" 奇葩说");
83 }else {
84 this.tv.play(" 播放广告");
85 }
86 }
87 }
88 }
89
90
91 class Watcher extends Thread{
92 Tv tv;
93
94 public Watcher(Tv tv) {
95 super();
96 this.tv = tv;
97 }
98 public void run(){
99 for (int i=0;i<20;i++) {
100 tv.watch();
101 }
102 }
103 }
原文:https://www.cnblogs.com/fangtingfei/p/11257865.html