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();
        }
    }
  • 相关阅读:
    关于开发BugRaid的想法(2)
    杭州.net俱乐部第一次见面会情况
    关于Bug管理的过程
    关于开发BugRaid的想法(1)
    变态的VS2005 SP1
    vs2003 sp1 download url
    proxy software
    敏捷开发
    Enterprise Library文档
    ETL
  • 原文地址:https://www.cnblogs.com/chiweiming/p/11168144.html
Copyright © 2011-2022 走看看