forked from 1904037-1904052/Banking-System
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOperationsQueue.java
67 lines (64 loc) · 2.47 KB
/
OperationsQueue.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
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class OperationsQueue {
private final List<Integer> operations = new ArrayList<>();
private final Lock lock = new ReentrantLock(true);
private boolean endofoperation = false, OnProcess1 = false, OnProcess2 = false;
public void addSimulation(int totalSimulation) {
// Add 50 random numbers in the operations list. The number will be range from -100 to 100. It cannot be zero.
for (int i = 0; i < totalSimulation; i++) {
int random = (int) (Math.random() * 200) - 100;
if (random != 0) {
operations.add(random);
System.out.println(i + ". New operation added: " + random);
}
// add small delay to simulate the time taken for a new customer to arrive
try {
Thread.sleep((int) (Math.random() * 80));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
endofoperation = true;
}
public void add(int amount) {
lock.lock();
try {
operations.add(amount);
ProcessDone();
} finally {
lock.unlock();
}
}
public synchronized void ProcessDone() {
if(OnProcess1 == true) OnProcess1 = false;
else OnProcess2 = false;
}
public synchronized int getNextItem() {
// add a small delay to simulate the time taken to get the next operation.
lock.lock();
try {
while (operations.isEmpty() && (endofoperation == false || OnProcess1 == true || OnProcess2 == true)) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println("OnCircle --- --- --- --- --- --- ---");
// System.out.println(OnProcess1);
// System.out.println(OnProcess2);
}
if(operations.isEmpty()) return -9999;
// System.out.println(Thread.currentThread().getName() + operations);
if(OnProcess1 == true) OnProcess2 = true;
else OnProcess1 = true;
// System.out.println(OnProcess1);
// System.out.println(OnProcess2);
return operations.remove(0);
} finally {
lock.unlock();
}
}
}