日期:2014-05-20 浏览次数:20923 次
public class Test1 
{
    
    public static void main(String[] args) throws Exception {
        AK_47 ak = new AK_47();
        In in = new In(ak);
        Out out = new Out(ak);
        new Thread(in).start();
        new Thread(out).start();
    }
    
    
}
class AK_47 {  //枪
    int max = 12;   //枪子弹最大数目
    int num = 0;    //当前子弹数目
    int in = 0;         //记录总共装了子弹数目
    int out = 0;      //记录总共射出子弹数目
    public  void in() {
        if(num==12) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        num++;
        in++;
        System.out.println("上子弹: "+num+"    "+"已经上子弹总数:"+in);
    }
    
    public void out() {
        if(num==0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        num--;
        out++;
        System.out.println("射子弹: "+num+"     "+"已经射子弹总数"+out);
    }
}
class Out implements Runnable {    //消费者
    AK_47 ak;
    public Out(AK_47 ak) {
        this.ak = ak;
    }
    public void run() {
        for(int i = 0; i < 30;i++) {
            synchronized(this.ak) {
                ak.out();
            }
        }
    }
}
class In implements Runnable {     //生产者
    AK_47 ak;
    public In(AK_47 ak) {
        this.ak = ak;
    }
    
    public void run() {
        for(int i =0; i< 30;i++) {
            synchronized(this.ak) {
                ak.in();
            }
        }
    }
}