IT虾米网

Java线程的通信怎么实现

kerrycode 2023年01月30日 编程语言 22 0
//协作模型——生产者消费者实现方式一——信号灯法//借助标志位----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; 
    } 
 
}

本文参考链接:https://www.yisu.com/zixun/540283.html
评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

Java装饰器怎么写