線程的通訊

//協做模型——生產者消費者實現方式一——信號燈法
//藉助標誌位----flag是關鍵

public class ThreadCopperator02 {
    public static void main(String[] args) {
        Tv tv=new Tv();
        new Watcher(tv).start();
        new Player(tv).start();


    }
}

//消費者 觀衆
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 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 Tv{
    String voice;
    //信號燈
    //若是爲true,則演員表演,觀衆等待
    //若是爲false,觀衆觀看,演員等待
    boolean flag=true;


    public synchronized  void play(String voice){
        //演員等待
        if(!flag){
            try {
                this.wait();//wait會釋放鎖
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //表演
        System.out.println("表演了"+voice);
        this.voice=voice;
        //喚醒了watch的線程的wait,從而執行下面的程序 ,從而輸出聽到了。。。        this.notifyAll();
        //切換標誌
        this.flag=!flag;

    }
//由於有鎖,因此線程要等待,一個一個地來
    public synchronized void watch(){

        //觀衆等待
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //觀看
        System.out.println("聽到了"+voice);
        //喚醒了play的線程的wait,從而執行下面的程序 ,從而輸出表演了。。。        this.notifyAll();
        //切換標誌
        this.flag=!flag;
    }

}
相關文章
相關標籤/搜索