2014年4月10日 星期四

練習 7: 多執行緒

續練習 6。現今有 3 個人共用一本活期存款的賬戶,而於同一個時間分別存入 500元、 1000元、 2000元,請顯示餘額 檔案:ATM.java
package bank2;

public class ATM extends Thread {
 DemandDepositAccount account;
 int money;
 
 public ATM(DemandDepositAccount account, int money){
  this.account = account;
  this.money = money;
 }
 
 public void run(){
  try {
   account.deposit(money);
  } catch (AccountException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}


檔案:Account.java
package bank2;

public abstract class Account {
 int balance;
 Account(int money) {
   balance = money;
 }
 public abstract int inquiry();
}


檔案:AccountException.java
package bank2;

public class AccountException extends Exception {
  
 public String getMessage() // 覆寫 Throwable 的 toString()
 {
  return "金額不可以為負數";
 }
 
 public void showMessage() { // 自定方法
  System.out.println("例外發生:請從新輸入金額");
 }
}


檔案:DemandDepositAccount.java
package bank2;

public class DemandDepositAccount extends Account {
 
 DemandDepositAccount(int money){
  super(money);
 }
 
 public synchronized void deposit(int money) throws AccountException {
  if (money < 0) {
   throw new AccountException();
  }
  else {
   balance += money;
   System.out.println("money: " +balance);
  }
 }
 
 public void withdraw(int money) throws AccountException{
  if (money < 0)
   throw new AccountException();
  else
   balance -= money;
 }

 public int inquiry() {
  return balance;
 }
}


檔案:FixedDepositAccount.java
package bank2;

public class FixedDepositAccount extends Account {

 FixedDepositAccount(int money) {
  super(money);
  try{
    if (money < 50000)
     throw new ArithmeticException("例外狀況:定期存款最少需 50,000 元");
  }catch(Exception e){
     System.out.println(e.toString());
  }
 }

 public FixedDepositAccount() {
  // TODO Auto-generated constructor stub
  super(50000);
 }

 @Override
 public int inquiry() {
  // TODO Auto-generated method stub
  (new FixedDepositAccount() {
   public void showMe(){
    System.out.println("本銀行定額存款10萬以上,另有優惠,請多加利用");
   }
  }).showMe();
  
  return balance;
 }
}


檔案:AccountTest.java
package bank2;

public class AccountTest {

 public static void main(String[] args) {

   DemandDepositAccount account1 = new DemandDepositAccount(1000);
   ATM A1 = new ATM(account1, 500);
   ATM A2 = new ATM(account1, 1000);
   ATM A3 = new ATM(account1, 2000);
   A1.start();
   A2.start();
   A3.start();
 }

}
執行結果













若 deposit ()這方法不用 synchronized 這修飾字時,會有不正常的顯示

沒有留言:

張貼留言