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

© 冯瀚冰 初级黑马   /  2012-4-8 10:51  /  2030 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class Resource

{

        private String name;

        private int count=1;

        private boolean flag =false;

        public synchronized void set(String name)

        {

          if(flag)

                  try{this.wait();}catch(Exception a){}

          this.name=name+"--"+count++;

         

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

          flag=true;

          this.notify();

        }

        public synchronized void out()

        {

          if(!flag)

         try{this.wait();}catch(Exception a){}

      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()

        {

          res.out();

        }

}

//------------------------------------

class ProduceConsumerDemo
{

        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();

        }

}

评分

参与人数 1技术分 +1 收起 理由
岳民喜 + 1

查看全部评分

4 个回复

倒序浏览
如图,你的t2线程没有放到循环里

p1.PNG (16.67 KB, 下载次数: 62)

p1.PNG

评分

参与人数 1技术分 +1 收起 理由
岳民喜 + 1

查看全部评分

回复 使用道具 举报
哦,谢谢
回复 使用道具 举报
难得一见的帖
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马