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



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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值