package com.test.Thread;//解决生产者消费者问题方法2:信号灯法publicclassTestPC2{publicstaticvoidmain(String[] args){
TV tv =newTV();newPlayer(tv).start();newWatcher(tv).start();}}//生产者:演员classPlayerextendsThread{
TV tv;publicPlayer(TV tv){this.tv = tv;}@Overridepublicvoidrun(){for(int i =0; i <20; i++){if(i%2==0){this.tv.play("快乐大本营");}else{this.tv.play("斗鱼");}}}}//消费者:观众classWatcherextendsThread{
TV tv;publicWatcher(TV tv){this.tv = tv;}@Overridepublicvoidrun(){for(int i =0; i <20; i++){
tv.watch();}}}//产品:电视节目classTV{//演员表演,观众等待 T//观众观看,演员等待 F
String voice;boolean flag =true;publicsynchronizedvoidplay(String voice){//观众观看,演员等待if(!flag){try{this.wait();}catch(InterruptedException e){
e.printStackTrace();}}//若观众没看,演员表演
System.out.println("演员表演了"+voice);//通知观众看this.notifyAll();this.voice=voice;this.flag=!this.flag;}//观看方法publicsynchronizedvoidwatch(){//演员表演观众等待if(flag){try{this.wait();}catch(InterruptedException e){
e.printStackTrace();}}
System.out.println("观看了:"+voice);//通知演员表演this.notifyAll();this.flag=!this.flag;}}