用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+'存款結(jié)束'); break;} }} }}class Total { public static int sum = 0;}
運行結(jié)果不是從100,200,......,到1800,中間總有重復的數(shù)字,但最后的結(jié)果總和是1800
問題解答
回答1:多個線程訪問同一個對象時,加synchronized(this)可以讓一個時間內(nèi)只有一個線程處理,但是你這里new了3個對象。
回答2:我感覺要懷疑的你的eclipse了,我完全復制的代碼,重新運行了一遍,結(jié)果是這樣的:沒有重復的數(shù)字,按照順序依次存錢啊,結(jié)果也是正確的
相關文章:
1. javascript - react+百度地圖2. html5 - iOS的webview加載出來的H5網(wǎng)頁,怎么修改html標簽select的樣式字體?3. vue.js - vue+webpack+vue-router 部署到nginx服務器下,非根目錄,前后端怎樣配置文件?4. javascript - 為什么當index等于5的時候,不在當前頁面跳轉(zhuǎn)到百度?不跳轉(zhuǎn)的代碼在倒數(shù)第五行5. angular.js - 關于angular react vue 我們在什么實際的開發(fā)項目中使用?如何選擇?6. 手動啟動mysql服務出錯,1067錯誤,如何解決呢?7. index.php錯誤,求指點8. 這是什么情況???9. 請教一條mysql的sql語句寫法;10. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯誤
