//测试:生产者消费者模型-->利用标志位解决:信号灯法publicclassProducerConsumer2{publicstaticvoidmain(String[] args){
TV tv =newTV();newAudience(tv).start();newActor(tv).start();}}//生产者->演员classActorextendsThread{
TV tv;publicActor(TV tv){this.tv = tv;}@Overridepublicvoidrun(){for(int i =0; i <20; i++){if(i%2==0){this.tv.play("乘风破浪的姐姐");}else{this.tv.play("妻子的浪漫旅行");}}}}//消费者->观众classAudienceextendsThread{
TV tv;publicAudience(TV tv){this.tv = tv;}@Overridepublicvoidrun(){for(int i =0; i <20; 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.voice = voice;//通知观众收看this.notifyAll();//通知唤醒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;}}
管程法:生产者-产品仓库-消费者模式//测试:生产者消费者模型-->利用缓冲区解决:管程法//生产者 消费者 产品 缓冲区public class ProducerConsumer { public static void main(String[] args) { SynContainer container = new SynContainer(); new Producer(container).start(); new Consu