欢迎光临散文网 会员登陆 & 注册

多线程协作--信号灯法

2021-02-10 11:30 作者:忘魂儿  | 我要投稿

//信号灯法 建立标志位
public class Exercise2 {
   public static void main(String[] args) {
       TvShow tvShow = new TvShow();
       new Play(tvShow).start();
       new Watcher(tvShow).start();
   }
}
//播放
class Play extends Thread{
   TvShow tvShow;

   public Play(TvShow tvShow) {
       this.tvShow = tvShow;
   }

   @Override
   public void run() {
       for (int i = 0; i < 20; i++) {
           if (i%2==0)
           {
              tvShow.Play("工作细胞");
           }
           else {
               tvShow.Play("紫罗兰花园");
           }
       }
   }
}
//观众
class Watcher extends Thread{
   TvShow tvShow;

   public Watcher(TvShow tvShow) {
       this.tvShow = tvShow;
   }

   @Override
   public void run() {
       for (int i = 0; i < 20; i++) {
           tvShow.Watch();
       }
   }
}
//节目
class TvShow{
   String program;
   boolean flag=true;
   public synchronized void Play(String program)
   {
       if (!flag)
       {
           try {
               this.wait();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
       System.out.println("播放了:"+program);
       this.notifyAll();
       this.program=program;
       this.flag=!this.flag;
   }
   public synchronized void Watch()
   {
       if (flag)
       {
           try {
               this.wait();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }

           System.out.println("观看了:"+program);
           this.notifyAll();
           this.flag=!this.flag;

   }
}

多线程协作--信号灯法的评论 (共 条)

分享到微博请遵守国家法律