首页 > 编程语言 > 详细

保证线程安全-信号灯法

时间:2021-03-09 09:27:12      阅读:28      评论:0      收藏:0      [点我收藏+]

保证线程安全-信号灯法

设立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;
?
  }
}

保证线程安全-信号灯法

原文:https://www.cnblogs.com/peanutist/p/14503005.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!