天天看點

生産者消費者問題2信号燈法

package com.test.Thread;
//解決生産者消費者問題方法2:信号燈法

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 < 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++) {
            tv.watch();

        }
    }
}
//産品:電視節目
class TV{
    //演員表演,觀衆等待 T
    //觀衆觀看,演員等待 F
    String voice;
    boolean flag =true;
    public synchronized  void play(String voice){
        //觀衆觀看,演員等待
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //若觀衆沒看,演員表演
        System.out.println("演員表演了"+voice);
        //通知觀衆看
        this.notifyAll();
        this.voice=voice;
        this.flag=!this.flag;

    }
    //觀看方法
    public synchronized  void watch(){
        //演員表演觀衆等待
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("觀看了:"+voice);
        //通知演員表演
        this.notifyAll();
        this.flag=!this.flag;


    }
}