
代號:
頁次:
-
以下 Java 程式模擬銀行帳戶存款與查詢餘額的多執行緒功能。Account
是帳戶類別,可以存款與查詢餘額;ATM 類別可以操作帳戶的存款功能;
Test 類別輸出查詢之最後帳戶餘額。
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.ArrayList;
class Account {
public void deposit(int m) { balance = balance + m; }
public int getBalance() { return balance; }
private int balance=0;
}
class ATM extends Thread {
public ATM(Account a, int m) {account = a; money = m;}
public void run() {
try {Thread.sleep(100);
} catch (InterruptedException e) { e.printStackTrace(); }
synchronized(Account.class) { account.deposit(money); }
//account.deposit(money);
}
private Account account;
private int money;
}
public class Test {
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> ts = new ArrayList<>();
Account account = new Account();
for(int i = 1 ; i <= 10 ; i++) {
Thread atm = new ATM(account, i);
atm.start();
ts.add(atm);
}
for(Thread t : ts) { t.join(); }
System.out.println("" + account.getBalance());
}
}
請說明此程式的執行緒之特性以及此程式輸出。(10 分)
將Line28 註解掉後,請說明程式執行結果與其運作原因。再將 Line13
註解掉,並打開 Line14,28 註解後,請說明此時程式執行結果與其運作
原因。(15 分)