- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransfer.java
More file actions
Latest commit
90 lines (77 loc) · 2.43 KB
/
Copy pathTransfer.java
File metadata and controls
90 lines (77 loc) · 2.43 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
packageBankingAppThreads;
importjava.util.concurrent.TimeUnit;
importjava.util.concurrent.locks.Lock;
importjava.util.concurrent.locks.ReentrantLock;
publicclassTransfers{
publicstaticvoidmain(String[] args) {
BankAccountaccount1 = newBankAccount("12345-678", 500.00);
BankAccountaccount2 = newBankAccount("98765-432", 1000.00);
newThread(newTransfer(account1, account2, 10.00), "Transfer1").start();
newThread(newTransfer(account2, account1, 55.88), "Transfer2").start();
}
}
classBankAccount {
privatedoublebalance;
privateStringaccountNumber;
privateLocklock = newReentrantLock();
BankAccount(StringaccountNumber, doublebalance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
publicbooleanwithdraw(doubleamount) {
if (lock.tryLock()) {
try {
// Simulate database access
Thread.sleep(100);
}
catch (InterruptedExceptione) {
}
balance -= amount;
System.out.printf("%s: Withdrew %f\n", Thread.currentThread().getName(), amount);
returntrue;
}
returnfalse;
}
publicbooleandeposit(doubleamount) {
if (lock.tryLock()) {
try {
// Simulate database access
Thread.sleep(100);
}
catch (InterruptedExceptione) {
}
balance += amount;
System.out.printf("%s: Deposited %f\n", Thread.currentThread().getName(), amount);
returntrue;
}
returnfalse;
}
publicbooleantransfer(BankAccountdestinationAccount, doubleamount) {
if (withdraw(amount)) {
if (destinationAccount.deposit(amount)) {
returntrue;
}
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);
}
}
returnfalse;
}
}
classTransferimplementsRunnable {
privateBankAccountsourceAccount, destinationAccount;
privatedoubleamount;
Transfer(BankAccountsourceAccount, BankAccountdestinationAccount, doubleamount) {
this.sourceAccount = sourceAccount;
this.destinationAccount = destinationAccount;
this.amount = amount;
}
publicvoidrun() {
while (!sourceAccount.transfer(destinationAccount, amount))
continue;
System.out.printf("%s completed\n", Thread.currentThread().getName());
}
}}