线程的通讯

//协做模型——生产者消费者实现方式一——信号灯法
//借助标志位----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;
    }

}
相关文章
相关标签/搜索