用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
問題解答
回答1:多個線程訪問同一個對象時,加synchronized(this)可以讓一個時間內只有一個線程處理,但是你這里new了3個對象。
回答2:我感覺要懷疑的你的eclipse了,我完全復制的代碼,重新運行了一遍,結果是這樣的:沒有重復的數字,按照順序依次存錢啊,結果也是正確的
相關文章:
1. macos - mac下docker如何設置代理2. java - 請問在main方法中寫成對象名.屬性()并賦值,與直接參參數賦值輸錯誤是什么原因?3. MySQL數據庫中文亂碼的原因4. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””5. docker不顯示端口映射呢?6. docker - 各位電腦上有多少個容器?。咳萜饕欢啵约憾几慊炝?,咋辦呢?7. android studio總是在processes running好久8. angular.js - 關于$apply()9. docker-compose 為何找不到配置文件?10. dockerfile - 我用docker build的時候出現下邊問題 麻煩幫我看一下
