-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBankAccount.java
More file actions
75 lines (70 loc) · 1.82 KB
/
BankAccount.java
File metadata and controls
75 lines (70 loc) · 1.82 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
package com.javaMultithreading;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private int accountNumber;
private double balance;
private double overdraftLimit;
private Lock lock = new ReentrantLock();
private List<Transcation> history = new ArrayList<>();
public BankAccount(int accountNumber, double balance, double overdraftLimit) {
this.accountNumber = accountNumber;
this.balance = balance;
this.overdraftLimit = overdraftLimit;
}
public int getAccountNumber() {
return accountNumber;
}
public Lock getLock() {
return lock;
}
public void deposit(double amount) {
lock.lock();
try {
balance +=amount;
history.add(new Transcation("Deposit",amount));
System.out.println(Thread.currentThread().getName()+"deposited"+amount+" to A/C"+ accountNumber);
}finally {
lock.unlock();
}
}
public boolean withdraw(double amount) {
lock.lock();
try {
if(balance- amount <-overdraftLimit) {
System.out.println(Thread.currentThread().getName()+"withdrawal denied (overdraft limit exceeded) A/C"+accountNumber);
return false;
}
balance-= amount;
history.add(new Transcation("withdraw", amount));
System.out.println(Thread.currentThread().getName()+"withdraw"+amount+ "from A/C"+accountNumber);
return true;
}
finally {
lock.unlock();
}
}
public double getBalance() {
lock.lock();
try {
return balance;
}
finally {
lock.unlock();
}
}
public void printTranscationHistory() {
lock.lock();
try {
System.out.println("Transcation History for A/C"+accountNumber);
for(Transcation t: history) {
System.out.println(t);
}
}
finally {
lock.unlock();
}
}
}