17、信号灯

 

 

 

package com.syn;
public class TestPc2 {
    public static void main(String[] args) {
        Tv tv = new Tv();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}
//生产者-演员
class Player extends Thread{
    Tv tv;
    public Player(Tv tv){
        this.tv=tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            if (i%2==0){
                this.tv.play("小品节目:"+i);
            }else {
                this.tv.play("大合唱节目:"+i);
            }
        }
    }
}
//消费者-观众
class Watcher extends Thread{
    Tv tv;
    public Watcher(Tv tv){
        this.tv=tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            tv.watch();
        }
    }
}
//产品-节目
class Tv{
    //演员表演,观众观看 true
    //观众等待,演员准备 false
    String programme;
    boolean flag=true;
    
    //表演
    public synchronized void play(String programme){
        if (!flag){
            try{
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        System.out.println("演员表演开始: "+programme);
        this.notifyAll(); //通知观众观看,唤醒
        this.programme=programme;
        this.flag=!this.flag;
    }
    //观看
    public synchronized void watch(){
        if (flag){
            try{
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        System.out.println("观众观看:"+programme);
        this.notifyAll(); //通知演员,开始表演
        this.flag=!this.flag;
    }
}

  

 

posted @ 2022-07-24 17:04  颓废且努力奋斗的人  阅读(11)  评论(0编辑  收藏  举报