黑马程序员技术交流社区

标题: 多线程 生产者和消费者 加锁问题,为什么没有结果 [打印本页]

作者: 王延龙    时间: 2013-7-30 17:25
标题: 多线程 生产者和消费者 加锁问题,为什么没有结果

//为什么,会没有结果,死锁吗?


class Resourse{

        private String name;
        private int num = 1;
        private boolean flag;

        public synchronized void set(String name){
       
                if(flag){
               
                        try{this.wait();} catch(InterruptedException e) {}
                }

                else{
               
                        this.name = name+num;
                        num++;

                        System.out.println(Thread.currentThread().getName()+"***生产者***"+this.name);

                        flag = true;
                        this.notify();
                }
        }

        public synchronized void get(){
       
                if(flag){
               
                        try{this.wait();}catch(InterruptedException e){}
                }

                else{

                        System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);

                        flag = false;
                        this.notify();
                }

        }
}

class Produce implements Runnable{

        Resourse r;

        public Produce(Resourse r){
       
                this.r = r;
        }

        public void run(){

                while(true){
               
                        r.set("馒头");
               
                }
        }
}

class Consumer implements Runnable{

        Resourse r;

        public Consumer(Resourse r){
       
                this.r = r;
        }

        public void run(){
       
                while(true){
               
                        r.get();
                }
        }
}

public class Show{

        public static void main(String[] args){
       
                Resourse r = new Resourse();

                Produce p = new Produce(r);
                Consumer c = new Consumer(r);

                Thread t1 = new Thread(p);
                Thread t2 = new Thread(c);

                t1.start();
                t2.start();
        }
}



作者: xkfxm    时间: 2013-8-5 10:55
看了半天终于找到了,在get()方法中的if()语句应该写成if(!flag)  ,
写成if(flag)导致set方法生产一个后flag改成true,生产者等待,然后消费者去判断为true也等待,导致线程全部等待,但不是死锁。。
另外小建议将notify()改为notifyAll(),这样多个生产者和消费者线程去操作时就不会产生线程全部等待的现象。notify()只是唤醒线程池中第一个等待的线程。




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