forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBankTransfer.java
More file actions
65 lines (55 loc) · 1.98 KB
/
Copy pathBankTransfer.java
File metadata and controls
65 lines (55 loc) · 1.98 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
class BankAccount {
private int balance;
public BankAccount(int balance) {
this.balance = balance;
}
public synchronized void deposit(int amount) {
balance += amount;
System.out.println(" deposited " + amount + ", new balance: " + balance);
}
public synchronized void withdraw(int amount) {
if (amount <= balance) {
balance -= amount;
System.out.println(" withdrew " + amount + ", new balance: " + balance);
} else {
System.out.println(" attempted to withdraw " + amount + ", but insufficient balance.");
}
}
public int getBalance() {
return balance;
}
}
class TransferTask implements Runnable {
private BankAccount fromAccount = new BankAccount(0);
private BankAccount toAccount;
private int amount;
public TransferTask(BankAccount fromAccount, BankAccount toAccount, int amount) {
this.fromAccount = fromAccount;
this.toAccount = toAccount;
this.amount = amount;
}
@Override
public void run() {
synchronized (fromAccount) {
synchronized (toAccount) {
if (fromAccount.getBalance() >= amount) {
fromAccount.withdraw(amount);
toAccount.deposit(amount);
System.out.println(" transferred " + amount + " from Account " + fromAccount + " to Account " + toAccount);
} else {
System.out.println(" failed to transfer " + amount + " due to insufficient balance.");
}
}
}
}
}
public class BankTransfer {
public static void main(String[] args) {
BankAccount account1 = new BankAccount(1000);
BankAccount account2 = new BankAccount(1000);
Thread thread1 = new Thread(new TransferTask(account1, account2, 300));
Thread thread2 = new Thread(new TransferTask(account2, account1, 500));
thread1.start();
thread2.start();
}
}