为什么不能实现 每进行一下写入之后 才能进行一次读出操作!
下面代码始终没能找出问题来!!请大家看看
package threadz;public class threadcon{
    public static void main(String args[]){
        Q q = new Q();
        new Thread(new put(q)).start();
         new Thread(new get(q)).start();    }
}
class Q{
   private String name,sex;
    boolean bfull=false;
   private int i=0;   public synchronized void producer(){
    if(bfull){
   try{
       wait();
   }
   catch(Exception e){
        }
  }
  else{
     if(i==0){ this.name="zlz";
         this.sex = "male";
         this.i=1;
     }
     if(i==1){
         this.name = "lili";
         this.sex = "female";
         this.i=0;
     }
      bfull=true;  }
 }
   public synchronized void consumer(){
       if(!bfull){
   try{
       wait();
   }
  catch(Exception e){
       }
  }
 else{
  System.out.println(this.name+" and "+this.sex);
  bfull=false;
  notify();
    }
 }
}
class put implements Runnable{
   private Q q=null;
   put(Q q){
       this.q=q;
   }
   public void run(){      while(true) q.producer();
    }
}
class get implements Runnable{
    private  Q q=null;
    get(Q q){
        this.q=q;
    }
    public void run(){
        while(true)
        q.consumer();
    }
}

解决方案 »

  1.   

    发生了死锁,当bfull=false时线程进入consumer(),此线程始终wait();
    修改方法,把producer()方法该为:
    public synchronized void producer(){
        if(bfull){
       try{
           wait();
       }
       catch(Exception e){
            }
      }
      else{
         if(i==0){ this.name="zlz";
             this.sex = "male";
             this.i=1;
         }
         else if(i==1){
             this.name = "lili";
             this.sex = "female";
             this.i=0;
         }
          bfull=true;
      notify();
         ~~~~~
      }
     }
      

  2.   

    我想实现轮流打印 zlz and mael  lili and female 
    这两句话 可是 
    结果总是打印 LILI AND FEMALE 
    不知道问题在哪里 情大家帮忙看看
      

  3.   

    你没仔细看我的程序啊!
    public synchronized void producer(){
        if(bfull){
       try{
           wait();
       }
       catch(Exception e){
            }
      }
      else{
         if(i==0){ this.name="zlz";
             this.sex = "male";
             this.i=1;
         }
         else if(i==1){
      ~~~~~
             this.name = "lili";
             this.sex = "female";
             this.i=0;
         }
          bfull=true;
      notify();
     ~~~~~
      }
     }
    看到了吗?不需要我解释为什么了吧,呵呵,以后写东西要细心.
      

  4.   

    还是不明白撒 说详细点撒 
    我刚学JAVA撒