黑马程序员技术交流社区

标题: 线程间的通信----对多个生产者和消费者问题补充 [打印本页]

作者: chenyanwei6    时间: 2016-12-23 21:26
标题: 线程间的通信----对多个生产者和消费者问题补充
package com.heima.code;
/*
4.如何能够使多个生产者和消费者的正常运行呢?
在代码中做如下修改之后,问题就解决了。在解决问题的过程中,就凸显了notifyAll方法的作用。(***必须掌握,开发中必不可少***)
请看程序InputOutputThreadDemo05
class ResourceDemo05{
      public synchronized void set(String name){
          while(flag)//把if(flag)修改成while(ture)
                        ...
                  this.notifyAll();//改成this.notifyAll();
      }

      public synchronized void out(){
          while(flag)//把if(flag)修改成while(ture)
                        ...
                  this.notifyAll();//改成this.notifyAll();
      }
}


总结:
对于多个生产者和消费者,为什么要定义while判断标记?
原因:让被唤醒的线程再一次判断标记。

为什么定义notifyAll()?
因为需要唤醒对方的线程。
只用notify,容易出现值唤醒奔放线程的情况。导致程序中的所有线程都等待。

*/
class ResourceDemo05{
        private String name;
        private int count;
        public boolean flag = false;
        public synchronized void set(String name){
                while(flag)
                        try {
                                this.wait();
                        } catch (Exception e) {}
                this.name = name+"......"+count++;
                System.out.println(Thread.currentThread().getName()+"++++++"+this.name);
                flag = true;
                this.notifyAll();
        }
        public synchronized void out(){
                while(!flag)
                        try {
                                this.wait();
                        } catch (Exception e) {}
                System.out.println(Thread.currentThread().getName()+"------"+this.name);
                flag = false;
                this.notifyAll();
        }
}
class ProducerDemo05 implements Runnable{
        private ResourceDemo05 resd05;
         ProducerDemo05(ResourceDemo05 resd05){
                this.resd05 = resd05;
        }
        @Override
        public  void run() {
                while(true){
                        resd05.set("商品");
                }
        }
}
class ConsumerDemo05 implements Runnable{
    private ResourceDemo05 resd05;
    ConsumerDemo05(ResourceDemo05 resd05){
            this.resd05 = resd05;
    }
        @Override
        public void run() {
                while(true){
                        resd05.out();
                }
        }
       
}
public class InputOutputThreadDemo05 {

        public static void main(String[] args) {
      ResourceDemo05 resd05 = new ResourceDemo05();

      ProducerDemo05 pro = new ProducerDemo05(resd05);
      ConsumerDemo05 con = new ConsumerDemo05(resd05);

      //新需求一,在需求的基础上进行增加生产者和消费者,以两个生产者和两个消费者为例
      Thread t1 = new Thread(pro);
      Thread t2 = new Thread(con);
      Thread t3 = new Thread(pro);
      Thread t4 = new Thread(con);

      t1.start();
      t2.start();
      t3.start();
      t4.start();

        }
}







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2