日期:2014-05-20  浏览次数:20730 次

又触礁了,高人来看看!

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

  }
}


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

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

------解决方案--------------------