zoukankan      html  css  js  c++  java
  • Java多线程学习——wait方法(信号灯法/生产者消费者模式)

    信号灯法:以一个标志位来判断是否执行还是等待

    public class TV {
        private String voice;   //内容
        private boolean flag=false;  //信号灯,true表示观众可以看电视啦,false表示演员可以表演啦
        //演员表演
        public synchronized void play(String voice){
            if(flag==true){   //true表示演员等待,观众观看
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //可以表演,此时flag=false
            System.out.println("表演了"+voice);
            this.voice=voice;
            flag=!flag; //表演完毕,改变flag=true,通知观众观看,同时让演员停止表演
            this.notifyAll();   //通知观众观看
        }
        //观众观看
        public synchronized void watch(){
            if(flag==false){    //false,观众不能观看
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //可以观看,此时flag=true;
            System.out.println("观看了"+voice);
            flag=!flag; //观看完毕,改变flag=false
            this.notifyAll();
        }
    }
    public class Player implements Runnable{
        private TV tv;
    
        public Player(TV tv) {
            this.tv = tv;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                if(i%2==0){
                    tv.play("中国好声音:"+i);
                }else{
                    tv.play("中国有嘻哈:"+i);
                }
            }
        }
    }
    public class Audience implements Runnable{
        private TV tv;
    
        public Audience(TV tv) {
            this.tv = tv;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                tv.watch();
            }
        }
    }
    public class TvTest {
        public static void main(String[] args) {
            TV tv=new TV();
            Player player=new Player(tv);
            Audience audience=new Audience(tv);
            new Thread(player).start();
            new Thread(audience).start();
        }
    }
  • 相关阅读:
    vm串口问题
    web测试和一般的应用程序测试的主要区别
    测试点总结<转>
    【转】.net正则表达式基础学习
    QTP场景恢复详解
    QTP之检查点实例操作(转载)
    Java使用JNI调用第三方dll动态链接库
    Android 2.2播放mp4视频提示“是无效的流媒体”的问题
    FileSystemWatch 对文件的监测 修改 创建 删除 并写入日志
    WinForm程序开机自动运行
  • 原文地址:https://www.cnblogs.com/chiweiming/p/11168144.html
Copyright © 2011-2022 走看看