首頁  >  問答  >  主體

用Java编写一个简单的存款

package desposit.money;

public class DespositMoney {

    public static void main(String[] args) {
        Customer c1 = new Customer("第一个顾客",3);
        Customer c2 = new Customer("第二个顾客",10); 
        Customer c3 = new Customer("第三个顾客",5); 

        c1.start();
        c2.start();
        c3.start();
    }

}

class Customer extends Thread{
    private int time;
    String s;
    public Customer(String s,int time){
        this.s = s;
        this.time = time;
    }
    public void run(){
        while(true)
        {
            synchronized(this){
                            
                if(time>0)    
                {
                    Total.sum+=100;
                    System.out.println(s+"存款100元,银行总共有存款"+Total.sum+"元");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    time --;
                }
                    
                if(time ==0)
                {
                    System.out.println(s+"存款结束");
                    break;
                }
            }
        }
    }    
    
}

class Total {
    public static int sum = 0;
}

运行结果不是从100,200,......,到1800,中间总有重复的数字,但最后的结果总和是1800

大家讲道理大家讲道理2743 天前460

全部回覆(2)我來回復

  • 怪我咯

    怪我咯2017-04-18 10:55:05

    多個執行緒存取同一個物件時,加上synchronized(this)可以讓一個時間內只有一個執行緒處理,但你這裡new了3個物件。

    回覆
    0
  • 阿神

    阿神2017-04-18 10:55:05

    我感覺要懷疑的你的eclipse了,我完全複製的程式碼,重新運行了一遍,結果是這樣的:
    沒有重複的數字,按照順序依次存錢啊,結果也是正確的

    回覆
    0
  • 取消回覆