首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

又撞礁了,高人来看看

2013-02-17 
又触礁了,高人来看看!class Producer implements Runnable{P qnullpublic Producer(P q){this.qq}publ

又触礁了,高人来看看!

class Producer implements Runnable
{
   P q=null;
   
   public Producer(P q)
   {
      this.q=q;   
   }
   
   
   public void run()
   {
      int i=0;
 
  while(true)
  {
     if(i==0)
 {
   q.set("Zhang San","Male");
 }
 else
 {
   q.set("Meimei","Female");
 }
   i=(i+1)%2;
  }

   
   }
  

}

class P
{
  
   
   private String name="meimei";   
   private String sex="female";
   
   boolean bFull=false;
   
   
   public synchronized void set(String name,String sex)
   {
 if(bFull)
 {
   try
   {wait();}
   catch(Exception e)
   {}
   
   this.name=name;

try
{
  Thread.sleep(10);
}
catch(Exception e)
{
   System.out.print(e.getMessage());
}

this.sex=sex;

bFull=true;


notify();
  
  }
   
}
   
   
   
   
public synchronized void get()
{
   if(!bFull)
 {
try{
wait();
 }
 catch(InterruptedException e)
 { }
 
 }  
 
 System.out.println(this.name+"---->"+this.sex); 
 bFull=false;

 notify();
 
 }
   
  
}


class Consumer implements Runnable
{
   P q; 
  
   public Consumer(P q)
   {
      this.q=q;
   }

   public void run()
   {
      while(true)
  {     
       q.get();  
  }
   
   }
    

}


public class ThreadCommun
{
  public static void main(String []args)
  {
    P q=new P();
    new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();

  }
}


本来是为了线程之间通讯以便 生产者和消费者 可以同步,即生产者生产一个,消费者就取走一个

但是现在一运行就一直在等待,没任何反应了,只有光标在闪
------解决方案--------------------


逻辑错了。。  if(!bFull)  if(bFull) 应该反过来
[解决办法]


[解决办法]

   public synchronized void set(String name,String sex)
   {
        if(bFull)
        {
            try
            {wait();}
            catch(Exception e)
            {}
        }//if 在着结束.bFull为假时,应该执行。
        this.name=name;
        try
        {
            Thread.sleep(10);
        }
        catch(Exception e)
        {
             System.out.print(e.getMessage());
        }
        this.sex=sex;
        bFull=true;
        notify();
   }

[解决办法]
把set方法中notify();后面的}放到
if(bFull)
 {
   try
   {wait();}
   catch(Exception e)
   {}
后面就是你想要的结果了

热点排行