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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 冯瀚冰 初级黑马   /  2012-4-8 10:51  /  1682 人查看  /  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, 下载次数: 40)

p1.PNG

评分

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

查看全部评分

回复 使用道具 举报
哦,谢谢
回复 使用道具 举报
最好不要用if,if只判断一次;
不过你这里只有一个生产者和消费者,没关系。

不要用notify(),要用notifyAll();
因为需要唤醒对方线程,只用notify,容易出现唤醒本方线程的情况,导致程序中的所有线程都等待。

class Consumer implements Runnable
{
        private Resource res;
        Consumer(Resource res)
        {
                this.res = res;
        }
        public void run()
        {
                while(true)//这里应该这样写
                {
                        res.out();
                }

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