您的位置:首頁技術文章
文章詳情頁

用Java編寫一個簡單的存款

瀏覽:99日期:2024-01-10 09:31:35

問題描述

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

問題解答

回答1:

多個線程訪問同一個對象時,加synchronized(this)可以讓一個時間內只有一個線程處理,但是你這里new了3個對象。

回答2:

我感覺要懷疑的你的eclipse了,我完全復制的代碼,重新運行了一遍,結果是這樣的:沒有重復的數字,按照順序依次存錢啊,結果也是正確的用Java編寫一個簡單的存款

標簽: java
相關文章:
国产综合久久一区二区三区