-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathBankAccountTest.java
More file actions
66 lines (55 loc) · 1.71 KB
/
Copy pathBankAccountTest.java
File metadata and controls
66 lines (55 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class BankAccount {
private int balance = 0;
public synchronized void deposit(int amount) {
balance += amount;
System.out.println(" deposited: " + amount + ", balance: " + balance);
}
public synchronized void withdraw(int amount) {
if (amount <= balance) {
balance -= amount;
System.out.println(" withdrew: " + amount + ", balance: " + balance);
} else {
System.out.println(" tried to withdraw: " + amount + ", but insufficient balance.");
}
}
public synchronized int getBalance() {
return balance;
}
}
class DepositTask implements Runnable {
private BankAccount account;
private int amount;
public DepositTask(BankAccount account, int amount) {
this.account = account;
this.amount = amount;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
account.deposit(amount);
}
}
}
class WithdrawTask implements Runnable {
private BankAccount account;
private int amount;
public WithdrawTask(BankAccount account, int amount) {
this.account = account;
this.amount = amount;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
account.withdraw(amount);
}
}
}
public class BankAccountTest {
public static void main(String[] args) {
BankAccount account = new BankAccount();
Thread depositThread = new Thread(new DepositTask(account, 100));
Thread withdrawThread = new Thread(new WithdrawTask(account, 50));
depositThread.start();
withdrawThread.start();
}
}