线程协作之信号灯法

源码

package com.lixi.lambda;

public class SignalLight {
    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 < 20; i++) {
            if(i%2==0){
                this.tv.play("快乐大本营");
            }else{
                this.tv.play("抖音");
            }

        }
    }
}
//消费者
class Watcher extends Thread{
    //构造方法
    TV tv;
    public Watcher(TV tv){
        this.tv=tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            this.tv.watch();
        }

    }
}
//资源
class TV{
    String Programmes;
    //生产者--为true
    //消费者--false
    //设置标志位
     boolean flag=true;
     //生产资源
    public synchronized void play(String Programmes){
        //flag为false时,等待
        if(!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员正在录制节目"+Programmes);
        //唤醒,开始执行消费者
        this.notify();
        //标志位更换
        this.flag=!this.flag;
        //更新
        this.Programmes=Programmes;
    }
    //消费资源
    public synchronized void watch(){
        //flag为真时,等待
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众正在观看节目"+Programmes);
        //消费完了,要开始生产
        this.notify();
        this.flag=!this.flag;
    }

}

运行结果

猜你喜欢

转载自blog.csdn.net/qq_47499256/article/details/121446028