-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBankAccount.java
112 lines (96 loc) · 2.1 KB
/
BankAccount.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package BankingAppThreads;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private double balance;
private String accountNumber;
private Lock lock;
public BankAccount(double initialBalance, String accountName) {
super();
this.balance = initialBalance;
this.accountNumber = accountNumber;
this.lock = new ReentrantLock();
}
// public void deposit(double amount){
// balance +=amount;
//
// }
//
// public void withdraw(double amount){
// balance -=amount;
// }
// public void deposit(double amount){
// synchronized(this) {
// balance +=amount;
// }
// }
//
// public void withdraw(double amount){
// synchronized(this){
// balance -=amount;
// }
// }
// public void withdrawn(double amount){
// lock.lock();
// try{
// balance-= amount;
// }finally {
// lock.unlock();
// }
// }
//
// public void deposit(double amount){
// lock.lock();
// try{
// balance+=amount;
// }finally{
// lock.unlock();
// }
// }
//using tryLock()
public void deposit(double amount){
boolean status = false;
try{
if(lock.tryLock(1000, TimeUnit.MILLISECONDS)){
try{
balance+=amount;
status= true;
}finally {
lock.unlock();
}
}else {
System.out.println("Could not get the lock");
}
} catch(InterruptedException e){
//do something here
}
System.out.println("Transaction status = "+ status);
}
public void withdraw(double amount){
boolean status = false;
try{
if(lock.tryLock(1000, TimeUnit.MILLISECONDS)){
try{
balance-=amount;
status =true;
}finally {
lock.unlock();
}
}else {
System.out.println("Could not get the lock");
}
} catch(InterruptedException e){
//do something here
}
System.out.println("Transaction status = "+status);
}
//method that gets the bank account number
public String getAccountNumber(){
return accountNumber;
}
//method that prints the bank account number
public void printAccountNumber() {
System.out.println("Account number = "+ accountNumber);
}
}