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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 靓仔 中级黑马   /  2013-10-29 09:28  /  936 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 靓仔 于 2013-10-29 21:56 编辑

class ProducerConsumerDemo
{
        public static void main(String args[])
        {
                Resource r=new Resource();
                Producer p=new Producer(r);
                Consumer c=new Consumer(r);
                Thread t1=new Thread(p);
                Thread t2=new Thread(c);
                Thread t3=new Thread(p);
                Thread t4=new Thread(c);
                t1.start();
                t2.start();
                t3.start();
                t4.start();
        }
}
class  Resource
{
        private String name;
        private int count = 1;
        private boolean flag;
        public synchronized void set(String name)
        {
                while(flag)//假如 t1先进来,t1为false,为什么不等待直接生产?这个问题一直没搞懂。
                        try{this.wait();} catch(Exception e){}
                this.name = name+"---"+count++;
                System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
                flag =true;
                this.notifyAll();
        }
        public synchronized void out()
        {
                while(!flag)
                        try{this.wait();} catch(Exception e){}
                System.out.println(Thread.currentThread().getName()+"-------消费者------"+this.name);
                        flag=false;
                        this.notifyAll();
        }
}
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();
                }
        }
}

评分

参与人数 1技术分 +1 收起 理由
To + 1 赞一个!

查看全部评分

5 个回复

倒序浏览
flag为false,条件不满足肯定跳出while循环啊,这有什么好疑问的?
回复 使用道具 举报
怎么跳出循环啊,假如t1先进来刚开始时false,不是wait等待吗,怎么跳?程序不就不运行了,一直在wait吗
回复 使用道具 举报
开始时,flag=false,相当于没有产品,while(false)跳过等待循环直接开始生产,
如果有产品,flag=true,此时线程进入set方法,while(true)等待产品被消费,即flag转变成false,跳出循环,开始生产

评分

参与人数 1技术分 +1 收起 理由
黄炳期 + 1

查看全部评分

回复 使用道具 举报
抓紧时间学习~
回复 使用道具 举报
To 金牌黑马 2013-10-29 21:44:10
地板
楼主你好,如果问题已解决请将帖子状态修改为提问结束,
如果未解决请继续追问,谢谢合作
修改方法请看解释帖:http://bbs.itheima.com/thread-89313-1-1.html
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马