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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张玉建 中级黑马   /  2013-7-30 18:06  /  1002 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 杨兴庭 于 2013-7-30 23:09 编辑

线程问题!这个代码,编译时没有问题,为什么在运行时什么都没有?求解释
class resource
{
private String name;
private boolean flag=false;
private int counnt=1;
public synchronized  void set(String name)
{
  
  while (flag)
  {
   try
   {
    this.wait();
   }
   catch (Exception e)
   {
    throw new RuntimeException("线程等待");
   }
   this.name= name+"...."+counnt++;
   System.out.println(Thread.currentThread().getName()+".生产.."+this.name);
   flag= true;
   this.notifyAll();
  }
}
public synchronized void get()
{
  System.out.println("hhhh");
  while(!flag)
  {
   try
   {
    this.wait();
   }
   catch (Exception e)
   {
    throw new RuntimeException("线程等待");
   }

   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.get();
  }
}
}
class  communication
{
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);
  //Thread t3=new Thread(pro);
  //Thread t4=new Thread(con);
  t1.start();
  t2.start();
  
  //t3.start();
  //t4.start();
}
}


3 个回复

倒序浏览
this.name=name+"...."+counnt++;
System.out.println(Thread.currentThread().getName()+".生产.."+this.name);
flag=true;
this.notifyAll();

把这些代码放到循环外边,另一个也是一样,我这里就不复制了

评分

参与人数 1技术分 +1 收起 理由
杨兴庭 + 1

查看全部评分

回复 使用道具 举报
谢谢!没注意到
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马