黑马程序员技术交流社区

标题: 毕老师讲的这个线程间通信,生产者与消费者,全部等待. [打印本页]

作者: zhou1234    时间: 2014-12-8 17:20
标题: 毕老师讲的这个线程间通信,生产者与消费者,全部等待.
class Produse
{
        private String name;
        private int counter=1;
        private boolean flag=false;
        public synchronized void set(String name)
        {
                if(flag)
                {
                        try
                        {
                                wait();
                        }
                        catch (Exception a)
                        {
                        }
                }
                this.name=name;
                System.out.println(Thread.currentThread().getName()+"///shengchan//////////"+counter);
                this.notify();//唤醒
                flag=true;//将标志位置真

       
        }
        public synchronized void get()
        {
                while(!flag)
                {
                        try
                        {
                                wait();
                        }
                        catch (Exception a)
                        {
                        }
                }
                System.out.println(Thread.currentThread().getName()+"///消费者////"+counter++);
                this.notify();
                flag=false;
        }
}

class ShengChan implements Runnable
{
        private Produse pro;
        ShengChan(Produse pro)
        {
                this.pro=pro;
       
        }
        public void run()
        {
                while(true)
                {
                pro.set("商品");//生产
                }
        }

}
class XiaoFei implements Runnable
{
        private Produse pro;
        XiaoFei(Produse pro)
        {
                this.pro=pro;
        }
        public void run()
        {
                        while(true)
                        {
                                pro.get();
                        }
        }
}

class  ProduseDemo
{
        public static void main(String[] args)
        {
                Produse pro=new Produse();
                ShengChan s=new ShengChan(pro);
                XiaoFei x=new XiaoFei(pro);
                Thread t1=new Thread(s);
                Thread t2=new Thread(s);
                Thread t3=new Thread(x);
                Thread t4=new Thread(x);
                t1.start();
                t2.start();
                t3.start();
                t4.start();
        }
毕老师讲的这个线程间通信,生产者与消费者,全部等待. 就是把if换成while,还用notify ,为什么会全部等待  弄不懂啊


作者: 桃华月禅    时间: 2014-12-8 17:48
因为如果哪一次生产的线程notify叫醒的是本方的另一个生产线程,那么不就是没有叫醒另一个线程之前直接判断标记等待了吗...
虽有JDK1.5后lock出现了,不是全部叫醒,而是只叫醒对方,增加一些效率




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