本帖最后由 王军行 于 2013-3-9 17:56 编辑
毕老师的生产者消费者例子:多个线程生产多个线程消费,老师讲到问题出现一个商品多消费或者漏消费商品是因为唤醒后没有再次判断标志,我第一时间想到的再在判断一次就是用两个if我尝试试了下没问题但是有没有点资源浪费我就不太清楚了,讲到while解决会出现全部睡死的时候,我又想到了把notify拿到while里面去。让他临等待之前唤醒一个。但是还是出现了程序死这是怎么回事我想不明白- class ProducerCunsumer
- {
- public static void main(String[] args)
- {
- Resource r = new Resource();
- Thread t1 = new Thread(new Producer(r));
- Thread t2 = new Thread(new Producer(r));
- Thread t3 = new Thread(new Cunsumer(r));
- Thread t4 = new Thread(new Cunsumer(r));
- t1.start();
- t2.start();
- t3.start();
- t4.start();
-
- }
- }
- class Resource
- {
- private String name;
- private int count = 0;
- private boolean flg = false;
- public synchronized void set(String name)
- {
- while(flg)
- {
- this.notify();
- try{wait();}catch (Exception e){}
- }
- this.name = name;
- count++;
- System.out.println(Thread.currentThread().getName()+"。。。生产者。。。"+name+count);
-
- flg = true;
- }
- public synchronized void out ()
- {
- while(!flg)
- {
- this.notify();
- try{wait();}catch (Exception e){}
- }
- System.out.println(Thread.currentThread().getName()+"。。消费者。。"+name+count);
- flg = false;
- }
- }
- class Producer implements Runnable
- { private Resource r;
- Producer(Resource r)
- {
- this.r = r;
- }
- public void run()
- {
- while (true)
- {
- r.set("商品");
- }
-
- }
- }
- class Cunsumer implements Runnable
- { private Resource r;
- Cunsumer(Resource r)
- {
- this.r = r;
- }
- public void run()
- {
- while (true)
- {
- r.out();
- }
- }
- }
复制代码 |
|