1. 程式人生 > 其它 >生產者消費者問題--訊號燈法:標誌位

生產者消費者問題--訊號燈法:標誌位

package com.kaka.thread;

//測試生產者消費者問題2--->訊號燈法:標誌位
public class TestPC2 {
    public static void main(String[] args) {
        TV tv=new TV();
        new Actor(tv).start();
        new Watcher(tv).start();
    }
}

//生產者-演員
class Actor extends Thread{
    TV tv=new TV();
    public Actor(TV tv){
        this.tv=tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
           //每兩個小時演員開始表演錄製
            if(i%2==0){
               this.tv.act("快樂大本營");
            }else{
                this.tv.act("廣告");
            }
        }
    }
}
//消費者-觀眾
class Watcher extends Thread{
    TV tv=new TV();
    public Watcher(TV tv){
        this.tv=tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            this.tv.watch();
        }
    }

}

//產品-節目
class TV{
    String voice;
    boolean flag=true;//演員白眼錄製時:true;觀眾觀看時:false

    //演員表演錄製
    public synchronized void act(String voice){

        if(!flag){
            try {
                this.wait();//當flag為false時,觀眾正在觀看,演員不能表演錄製活動,因此等待,釋放鎖
            } 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();//flag為真時,演員正在錄製表演,因此觀眾無法觀看,需要等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("觀眾觀看了:"+voice);
        //通知演員表演
        this.notifyAll();
        this.flag=!this.flag;
    }
}