保证线程安全-信号灯法

设立flag,一个线程flag=true时跑,另一个线程wait(),跑完了告诉另外一个线程可以跑了notifyAll()

public class TestThreadWait2 {
   public static void main(String[] args) {
       TV tv = new TV();
       new Actor(tv).start();
       new Viewer(tv).start();
  }
}
//生产者-》演员
class Actor extends Thread{
   TV tv;

   public Actor(TV tv) {
       this.tv = tv;
  }

   @Override
   public void run() {
       for (int i = 0; i < 10; i++) {
           if (i%2==0){
               this.tv.play("新闻联播");
          }else {
               this.tv.play("焦点访谈");
          }
      }

  }
}
//消费者-》观众
class Viewer extends Thread{
   TV tv;

   public Viewer(TV tv) {
       this.tv = tv;
  }

   @Override
   public void run() {
       for (int i = 0; i < 20; i++) {
           tv.watch();
      }
  }
}
//产品-》节目
class TV{
   String product;
   boolean flag=true;

   public synchronized void play(String product){
       if (!flag){
           try {
               this.wait();
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
      }
           System.out.println("演员正在表演"+product);
           //通知观众可以看了
           this.notifyAll();
           this.product=product;
           this.flag=!this.flag;

  }

   public synchronized void watch(){
       if (flag){
           try {
               this.wait();
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
      }
           System.out.println("观众观看了"+product);
           //通知演员可以演了
           this.notifyAll();
           this.flag=!this.flag;

  }
}
posted on 2021-03-08 23:12  要给小八赚罐头钱  阅读(40)  评论(0)    收藏  举报