Java零基础学java之多线程--22生产者消费者问题:信号灯法

package com.li;

//测试:生产者消费者问题  --> 信号灯法
//电视台(节目,广告)、观众、电视
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%2==0) {
                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);
        //观众看完了节目,通知电视台
        this.notifyAll();
        this.flag = !this.flag;

    }
}

猜你喜欢

转载自blog.csdn.net/l1341886243/article/details/118424625