信号灯法:以一个标志位来判断是否执行还是等待
public class TV { private String voice; //内容 private boolean flag=false; //信号灯,true表示观众可以看电视啦,false表示演员可以表演啦 //演员表演 public synchronized void play(String voice){ if(flag==true){ //true表示演员等待,观众观看 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //可以表演,此时flag=false System.out.println("表演了"+voice); this.voice=voice; flag=!flag; //表演完毕,改变flag=true,通知观众观看,同时让演员停止表演 this.notifyAll(); //通知观众观看 } //观众观看 public synchronized void watch(){ if(flag==false){ //false,观众不能观看 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //可以观看,此时flag=true; System.out.println("观看了"+voice); flag=!flag; //观看完毕,改变flag=false this.notifyAll(); } }
public class Player implements Runnable{ private TV tv; public Player(TV tv) { this.tv = tv; } @Override public void run() { for (int i = 0; i < 20; i++) { if(i%2==0){ tv.play("中国好声音:"+i); }else{ tv.play("中国有嘻哈:"+i); } } } }
public class Audience implements Runnable{ private TV tv; public Audience(TV tv) { this.tv = tv; } @Override public void run() { for (int i = 0; i < 20; i++) { tv.watch(); } } }
public class TvTest { public static void main(String[] args) { TV tv=new TV(); Player player=new Player(tv); Audience audience=new Audience(tv); new Thread(player).start(); new Thread(audience).start(); } }