forked from 1904037-1904052/Banking-System
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBank.java
66 lines (57 loc) · 2.35 KB
/
Bank.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
public class Bank {
String accountNumber;
OperationsQueue operationsQueue;
private final Object lock = new Object();
int balance = 0;
public Bank(String accountNumber, OperationsQueue operationsQueue) {
this.accountNumber = accountNumber;
this.operationsQueue = operationsQueue;
}
// A deposit function that will run in parallel on a separate thread. It will be a loop where in each iteration, it read the amount from the operationQueue and deposit the amount.
public void deposit() {
//TIP Press <shortcut actionId="Debug"/> to start debugging your code. We have set one <icon src="AllIcons.Debugger.Db_set_breakpoint"/> breakpoint
// for you, but you can always add more by pressing <shortcut actionId="ToggleLineBreakpoint"/>.
while (true) {
int amount = operationsQueue.getNextItem();
if(amount == -9999) {
break;
}
if (amount>0) {
synchronized(lock) {
balance = balance + amount;
operationsQueue.ProcessDone();
}
System.out.println("Deposited: " + amount + " Balance: " + balance);
}
else{
operationsQueue.add(amount);
System.out.println("operation added back "+amount);
}
}
}
// A withdraw function that will run in parallel on a separate thread. It will be a loop where in each iteration, it read the amount from the operationQueue and withdraw the amount.
public void withdraw() {
while (true) {
int amount = operationsQueue.getNextItem();
if(amount == -9999) {
break;
}
if(balance+amount<0){
operationsQueue.ProcessDone();
System.out.println("Not enough balance to Withdrawn "+amount);
continue;
}
if (amount<0) {
synchronized(lock) {
balance = balance + amount;
operationsQueue.ProcessDone();
}
System.out.println("Withdrawn: " + amount + " Balance: " + balance);
}
else{
operationsQueue.add(amount);
System.out.println("operation added back "+amount);
}
}
}
}