java多线程之生产者消费者模式

来源:互联网 发布:千古乎评证券之星 编辑:程序博客网 时间:2024/06/05 01:06

public class ProductAndCustomer{    /**     * 存放基本信息的Info类。     * flag为判断是否可以生产或者消费的标记     * flag=true 表示可以生产,但是不能取走     *flag=false 表示可以取走,但是不能生产     */    static class Info{        private String name;        private  String sex;        //判断是否可以生产的标记        //flag=true 表示可以生产,但是不能取走        //flag=false 表示可以取走,但是不能生产        private boolean flag=true;        public synchronized void set(String name,String sex){            /**             * 生产前,查看标记,如果flag=false,则证明上一次的生产的“货物”尚未取走,要等待“货物”取走后             *才能进行生产。             */          if(this.flag==false){              try {                  super.wait();              } catch (InterruptedException e) {                  e.printStackTrace();              }          }            this.name=name;            try {                Thread.sleep(200);            } catch (InterruptedException e) {                e.printStackTrace();            }            this.sex=sex;            //生产完成后,修改flag标记为false。告诉“消费者”可以购买了。            this.flag=false;            //唤醒正在等待的线程            super.notify();        }        public synchronized  void get(){            /**             *  要取走前,查看flag标记,如果flag=true,则证明”库存不足“,要等待生产完成后才能取走             */            if(this.flag==true){                try {                    super.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            try {                Thread.sleep(100);            } catch (InterruptedException e) {                e.printStackTrace();            }            //生产的“货物”被取走后,修改flag标记,告诉生产者:”嘿,哥们,赶紧起来干活了!仓库里没货啦"            this.flag=true;            //唤醒正在等待的线程            super.notify();            System.out.println(this.name+","+this.sex);        }    }    static class Proudct implements Runnable{        private  Info info;        public Proudct(Info info){            this.info=info;        }        @Override        public void run() {            for(int i=1;i<=100;i++){                if(i%2==0){                    this.info.set("李朝宇","男");                }else{                    this.info.set("王桂花","女");                }            }        }    } static class Customer implements Runnable{      private Info info;      public Customer(Info info){          this.info=info;      }        @Override        public void run() {          for(int i=1;i<=100;i++){              this.info.get();          }        }    }    public static void  main(String[] args) {     Info info =new Info();     new Thread(new Proudct(info)).start();     new Thread(new Customer((info))).start();    }}
原创粉丝点击