黑马程序员技术交流社区

标题: 毕老师多线程通信的代码疑问?疑问在代码注释中。 [打印本页]

作者: 没有翅膀的小鸟    时间: 2014-7-4 22:34
标题: 毕老师多线程通信的代码疑问?疑问在代码注释中。
class ProConTest
{
        public static void main(String[] args)
        {
                Resource r=new Resource();

                Producer pro=new Producer(r);
                Consumer con=new Consumer(r);

                Thread t1=new Thread(pro);
                Thread t2=new Thread(con);

                t1.start();
                t2.start();
        }
}
class Resource
{
        private String name;
        private int id=1;
        private boolean flag=false;
        public synchronized void set(String name)
        {
                if(flag)
                        try{this.wait();}catch(Exception e){}
                this.name=name+"..."+id++;
                System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
                flag=true;
                this.notify();
        }
        public synchronized void out()
        {
                if(!flag)
                        try{this.wait();}catch(Exception e){}
                System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
                flag=false;
                this.notify();

        }
}
class Producer implements Runnable
{
        //这一句代码和下面的构造函数的作用是让生产者和消费者使用的是同一个资源对象。
        //为什么可以起到这个作用?还是有点不明白。
        private Resource res;
        Producer(Resource res)
        {
                this.res=res;
        }
        public void run()
        {
                while(true)
                {
                        res.set("商品");
                }
        }
}
class Consumer implements Runnable
{
        private Resource res;
        Consumer(Resource res)
        {
                this.res=res;

        }
        public void run()
        {
                while(true)
                {
                        res.out();
                }
        }
}
作者: LeaonButcher    时间: 2014-7-4 23:18
public static void main(String[] args)
        {
                Resource r=new Resource();       //这个就是你创建的资源

                Producer pro=new Producer(r);  //然后作为参数传递给生产者
                Consumer con=new Consumer(r);//同样传递给消费者;生产者和消费者拿到的是同一个资源

                Thread t1=new Thread(pro);
                Thread t2=new Thread(con);

                t1.start();
                t2.start();
        }
作者: 燿陚√揚葳    时间: 2014-7-5 11:01
同意楼上.......
作者: 西地那非    时间: 2014-7-5 12:49
public synchronized void out()
        {
                if(!flag)
                        try{this.wait();}catch(Exception e){}
                System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
                flag=false;
                this.notify();

        }
这里面所用的锁,就是res这个对象的锁。




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