-
Notifications
You must be signed in to change notification settings - Fork 0
/
Transfer.java
90 lines (77 loc) · 2.43 KB
/
Transfer.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package BankingAppThreads;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Transfers{
public static void main(String[] args) {
BankAccount account1 = new BankAccount("12345-678", 500.00);
BankAccount account2 = new BankAccount("98765-432", 1000.00);
new Thread(new Transfer(account1, account2, 10.00), "Transfer1").start();
new Thread(new Transfer(account2, account1, 55.88), "Transfer2").start();
}
}
class BankAccount {
private double balance;
private String accountNumber;
private Lock lock = new ReentrantLock();
BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public boolean withdraw(double amount) {
if (lock.tryLock()) {
try {
// Simulate database access
Thread.sleep(100);
}
catch (InterruptedException e) {
}
balance -= amount;
System.out.printf("%s: Withdrew %f\n", Thread.currentThread().getName(), amount);
return true;
}
return false;
}
public boolean deposit(double amount) {
if (lock.tryLock()) {
try {
// Simulate database access
Thread.sleep(100);
}
catch (InterruptedException e) {
}
balance += amount;
System.out.printf("%s: Deposited %f\n", Thread.currentThread().getName(), amount);
return true;
}
return false;
}
public boolean transfer(BankAccount destinationAccount, double amount) {
if (withdraw(amount)) {
if (destinationAccount.deposit(amount)) {
return true;
}
else {
// The deposit failed. Refund the money back into the account.
System.out.printf("%s: Destination account busy. Refunding money\n",
Thread.currentThread().getName());
deposit(amount);
}
}
return false;
}
}
class Transfer implements Runnable {
private BankAccount sourceAccount, destinationAccount;
private double amount;
Transfer(BankAccount sourceAccount, BankAccount destinationAccount, double amount) {
this.sourceAccount = sourceAccount;
this.destinationAccount = destinationAccount;
this.amount = amount;
}
public void run() {
while (!sourceAccount.transfer(destinationAccount, amount))
continue;
System.out.printf("%s completed\n", Thread.currentThread().getName());
}
}}