thinking in java里有的讲

解决方案 »

  1.   

    下面是一个线程同步问题,你好好体会一下吧!class q {//产生同步序列
       int n;
       boolean val=false;
       synchronized int get(){
         if(!val){
           try{
             wait();
             }catch(java.lang.InterruptedException e){}
         }     System.out.println("get: "+n);
         val=false;
         notify();
         return n;
       }   synchronized int put(int n){
         if(val){
           try{
             wait();
             }catch(java.lang.InterruptedException e){}
         }
         this.n=n;
         val=true;
         System.out.println("put:"+n);     notify();
         return n;
       }
    }class pro implements Runnable{//生产者
      q q1;  pro(q q1){
        this.q1=q1;
        new Thread(this).start();
      }  public void run(){
        int i=0;
        while(i!=5)
        try{
          q1.put(i++);
          Thread.sleep(1000);
        }catch(java.lang.InterruptedException e){}
      }
    }
    class cust implements Runnable{//消费者
      q q1;
      cust(q q1){
        this.q1=q1;
        new Thread(this).start();
      }  public void run(){
        while(true){
          q1.get();
        }
      }
      public static void main(String[] args) {
        q q1=new q();
        new pro(q1);
        new cust(q1);
      }
    }