package cn.itcast.day0827.java线程安全;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 <200; i++){if(i%2==0){this.tv.play("节目1");}else{this.tv.play("节目2");}}}}//观众类classWatcherextendsThread{
TV tv;publicWatcher(TV tv){this.tv=tv;}@Overridepublicvoidrun(){for(int i =0; i <100; i++){
tv.watch();}}}//节目类classTV{
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;}}