forked from george-ezat/Java-Concurrent-Service-Station
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceStation.java
More file actions
306 lines (247 loc) · 9.65 KB
/
Copy pathServiceStation.java
File metadata and controls
306 lines (247 loc) · 9.65 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;
import java.util.Queue;
import java.util.Scanner;
// ==============================================
class Semaphore {
private int value;
public Semaphore(int value) {
this.value = value;
}
public synchronized int getValue() {
return value;
}
/**
* Waits (decrements) the semaphore.
* If the value is 0, the thread blocks until another thread signals.
*/
public synchronized void semaphoreWait() {
while (value == 0) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
value--;
}
/**
* Signals (increments) the semaphore.
* Notifies one waiting thread.
*/
public synchronized void semaphoreSignal() {
value++;
notify();
}
}
// ==============================================
/**
* Represents a Pump (Consumer).
* A pump waits for a car to be in the queue, services it, and then releases the
* pump bay.
*/
class Pump implements Runnable {
private int pumpId;
private Queue<Car> waitingQueue;
private Semaphore empty, full, mutex, pumps, finished;
public Pump(int pumpId, Queue<Car> waitingQueue, Semaphore empty, Semaphore full, Semaphore mutex, Semaphore pumps,
Semaphore finished) {
this.pumpId = pumpId;
this.waitingQueue = waitingQueue;
this.empty = empty;
this.full = full;
this.mutex = mutex;
this.pumps = pumps;
this.finished = finished;
}
@Override
public void run() {
// Pump threads run indefinitely, controlled by the main thread
while (true) {
// 1. Wait for a free pump bay first.
pumps.semaphoreWait();
// 2. Wait for a car to be in the queue.
full.semaphoreWait();
// 3. Lock the queue to take a car.
mutex.semaphoreWait();
Car car = waitingQueue.poll();
if (car != null) {
System.out.println("Pump " + pumpId + ": " + car.getName() + " occupied");
}
mutex.semaphoreSignal();
// 4. Signal that a waiting area spot is now free.
empty.semaphoreSignal();
// --- Service Logic ---
if (car != null) {
System.out.println("Pump " + pumpId + ": " + car.getName() + " login");
System.out.println("Pump " + pumpId + ": " + car.getName() + " begins service at Bay " + pumpId);
try {
// Simulate service time
Thread.sleep(4000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Pump " + pumpId + ": " + car.getName() + " finishes service");
System.out.println("Pump " + pumpId + ": Bay " + pumpId + " is now free");
}
// --- End Service Logic ---
// 5. Signal to the main thread that one car has finished service.
finished.semaphoreSignal();
// 6. Release the pump bay.
pumps.semaphoreSignal();
}
}
}
// ==============================================
/**
* Represents a Car (Producer).
* A car arrives, waits for a spot in the waiting area, and then enters the
* queue.
*/
class Car implements Runnable {
private String name;
private Queue<Car> waitingQueue;
private Semaphore empty, full, mutex;
public Car(String name, Queue<Car> waitingQueue, Semaphore empty, Semaphore full, Semaphore mutex) {
this.name = name;
this.waitingQueue = waitingQueue;
this.empty = empty;
this.full = full;
this.mutex = mutex;
}
@Override
public void run() {
// 1. Car arrives
System.out.println("Car " + this.name + " arrived");
// 2. Wait for a free spot in the waiting area.
empty.semaphoreWait();
// 3. Lock the queue to enter.
mutex.semaphoreWait();
waitingQueue.add(this);
// 4. Print message for "Enters the queue" / "waiting"
System.out.println("Car " + name + " entered the queue and is waiting");
mutex.semaphoreSignal();
// 5. Signal to a pump that a car is in the queue.
full.semaphoreSignal();
}
public String getName() {
return name;
}
}
// ==============================================
class ServiceStation {
private int waitingAreaCapacity;
private int numPumps;
private Queue<Car> waitingQueue;
private Semaphore empty, full, pumps, mutex, finished;
// ------------------------------------------
public ServiceStation(int capacity, int numPumps) {
this.waitingAreaCapacity = capacity;
this.numPumps = numPumps;
this.waitingQueue = new LinkedList<>();
this.mutex = new Semaphore(1); // Controls access to the queue
this.empty = new Semaphore(capacity); // Counts empty spots in waiting area
this.full = new Semaphore(0); // Counts cars in waiting area
this.pumps = new Semaphore(numPumps); // Counts available pumps
this.finished = new Semaphore(0); // Starts at 0, will be signaled `totalCars` times.
}
// ------------------------------------------
public void runSimulation(String[] carNames) {
System.out.println(
"Simulation started with " + numPumps + " pumps and " + waitingAreaCapacity + " waiting spots.");
// Start all the pump threads
for (int i = 1; i <= numPumps; i++) {
Thread pumpThread = new Thread(new Pump(i, waitingQueue, empty, full, mutex, pumps, finished));
pumpThread.setDaemon(true);
pumpThread.start();
}
// Keep track of car threads to ensure they all start.
List<Thread> carThreads = new ArrayList<>();
for (String name : carNames) {
Thread carThread = new Thread(new Car(name, waitingQueue, empty, full, mutex));
carThreads.add(carThread);
carThread.start();
try {
// Stagger car arrivals
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 1. Wait for all Car threads to finish (i.e., all cars have *arrived*).
for (Thread t : carThreads) {
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 2. Wait for all cars to be *serviced*.
// The main thread will block here until `finished.semaphoreSignal()`
// has been called `carNames.length` times by the pump threads.
for (int i = 0; i < carNames.length; i++) {
finished.semaphoreWait();
}
System.out.println("All cars processed; simulation ends.");
}
// ------------------------------------------
public static int getValidatedInt(Scanner scanner, String message, int min, int max) {
int number = 0;
while (true) {
try {
System.out.print(message);
number = scanner.nextInt();
if (number >= min && number <= max) {
break;
} else {
System.out.println(
"Error: Please enter a number between " + min + " and " + max + ".");
}
} catch (InputMismatchException e) {
System.out.println("Error: Invalid input. Please enter a whole number.");
scanner.next();
}
}
return number;
}
// ------------------------------------------
public static String[] getValidatedCars(Scanner scanner, String message) {
String[] carNames;
while (true) {
System.out.print(message);
String carInput = scanner.nextLine();
if (carInput == null || carInput.trim().isEmpty()) {
System.out.println("Error: Input cannot be empty. Please enter at least one car name.");
continue;
}
// remove all whitespace and split
carNames = carInput.replaceAll("\\s+", "").split(",");
// if the split resulted in empty strings (user typed: "," or " , , ")
List<String> validNames = new ArrayList<>();
for (String name : carNames) {
if (name != null && !name.trim().isEmpty()) {
validNames.add(name.trim());
}
}
if (validNames.isEmpty()) {
System.out.println("Error: Invalid format. Please enter car names (e.g., C1, C2).");
continue;
}
return validNames.toArray(new String[0]);
}
}
// ------------------------------------------
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int waitingAreaCapacity = getValidatedInt(scanner, "Enter waiting area capacity (1-10): ", 1, 10);
int numPumps = getValidatedInt(scanner, "Enter number of service bays (pumps): ", 1, Integer.MAX_VALUE);
// c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12
scanner.nextLine();
String[] carNames = getValidatedCars(scanner, "Enter car arrivals separated by commas (e.g., C1, C2, C3): ");
ServiceStation station = new ServiceStation(waitingAreaCapacity, numPumps);
station.runSimulation(carNames);
scanner.close();
}
}