生产者消费者问题:信号灯法

package com.liu.gaoji;

//测试:生产者消费者问题  --> 信号灯法
//电视台(节目,广告)、观众、电视
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        TVStation tvStation = new TVStation(tv);
        Audience audience = new Audience(tv);
        tvStation.start();
        audience.start();
    }
}
//电视台
class TVStation extends Thread{
    TV tv;
    public TVStation(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if (i%3==0) {
                try {
                    this.tv.play("西虹市首富");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else if(i%3==1){
                try {
                    this.tv.play("大江大河");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                try {
                    this.tv.play("家有儿女");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
//观众
class Audience extends Thread{
    TV tv;
    public Audience(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                tv.watch();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//电视
class TV {
    //电视台准备播放节目,观众等待 T
    //观众看节目,电视台等待 F
    String program;//节目
    boolean flag = true;

    //电视台准备播放节目
    public synchronized void play(String program) throws InterruptedException {
        if (!flag) {
            //观众观看,电视台等待
            this.wait();
        }
        //电视台准备节目
        System.out.println("电视台准备了节目:" + program);
        this.notifyAll();//通知观众
        this.program = program;
        this.flag = !this.flag;//刷新标志位
    }

    //观众看节目
    public synchronized void watch() throws InterruptedException {
        if (flag) {
            //电视台准备节目,观众等待
            this.wait();
        }
        System.out.println("观众观看了节目:" + program);
        System.out.println();
        //观众看完了节目,通知电视台
        this.notifyAll();
        this.flag = !this.flag;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值