A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 王军行 于 2013-3-9 17:56 编辑

毕老师的生产者消费者例子:多个线程生产多个线程消费,老师讲到问题出现一个商品多消费或者漏消费商品是因为唤醒后没有再次判断标志,我第一时间想到的再在判断一次就是用两个if我尝试试了下没问题但是有没有点资源浪费我就不太清楚了,讲到while解决会出现全部睡死的时候,我又想到了把notify拿到while里面去。让他临等待之前唤醒一个。但是还是出现了程序死这是怎么回事我想不明白
  1. class  ProducerCunsumer
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 Resource r = new Resource();
  6.                 Thread t1 = new Thread(new Producer(r));
  7.                 Thread t2 = new Thread(new Producer(r));
  8.                 Thread t3 = new Thread(new Cunsumer(r));
  9.                 Thread t4 = new Thread(new Cunsumer(r));
  10.                 t1.start();
  11.                 t2.start();
  12.                 t3.start();
  13.                 t4.start();
  14.                
  15.         }
  16. }
  17. class Resource
  18. {
  19.         private String name;
  20.         private int  count = 0;
  21.         private boolean flg = false;
  22.         public synchronized void set(String name)
  23.         {
  24.                 while(flg)
  25.                 {
  26.                         this.notify();
  27.                         try{wait();}catch (Exception e){}
  28.                 }                        
  29.                 this.name = name;
  30.            count++;
  31.                 System.out.println(Thread.currentThread().getName()+"。。。生产者。。。"+name+count);
  32.                
  33.                 flg = true;        
  34.         }
  35.         public synchronized void out ()
  36.         {
  37.                 while(!flg)
  38.                 {
  39.                         this.notify();
  40.                         try{wait();}catch (Exception e){}
  41.                 }
  42.                 System.out.println(Thread.currentThread().getName()+"。。消费者。。"+name+count);
  43.                 flg = false;        
  44.         }
  45. }
  46. class Producer implements Runnable
  47. { private Resource r;
  48.         Producer(Resource r)
  49.         {
  50.                 this.r = r;
  51.         }
  52.   public void run()
  53.         {
  54.           while (true)
  55.           {
  56.                   r.set("商品");
  57.           }
  58.          
  59.         }

  60. }
  61. class Cunsumer implements Runnable
  62. { private Resource r;
  63.         Cunsumer(Resource r)
  64.         {
  65.                 this.r = r;
  66.         }
  67.   public void run()
  68.         {
  69.           while (true)
  70.                 {        
  71.                         r.out();
  72.                 }
  73.         }

  74. }
复制代码

3 个回复

倒序浏览
本身的生产者线程与 其他的阻塞状态消费者线程都给唤醒了,cpu执行切换到生产者,就产生了虚假唤醒...
回复 使用道具 举报


这个。。。。。{:soso_e127:}
回复 使用道具 举报
while(!flg)
                {
                        this.notify();

//想明白点了,这里是两句,cpu在这里切换执行权就会出问题
                        try{wait();}catch (Exception e){}
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马