-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Expand file tree
/
Copy pathTrafficControlSystem.java
More file actions
53 lines (45 loc) · 1.91 KB
/
TrafficControlSystem.java
File metadata and controls
53 lines (45 loc) · 1.91 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
package trafficsignalcontrolsystem;
import trafficsignalcontrolsystem.observer.CentralMonitor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TrafficControlSystem {
private static final TrafficControlSystem INSTANCE = new TrafficControlSystem();
private final List<IntersectionController> intersections = new ArrayList<>();
private ExecutorService executorService;
private TrafficControlSystem() {}
public static TrafficControlSystem getInstance() {
return INSTANCE;
}
public void addIntersection(int intersectionId, int greenDuration, int yellowDuration) {
IntersectionController intersection = new IntersectionController.Builder(intersectionId)
.withDurations(greenDuration, yellowDuration)
.addObserver(new CentralMonitor())
.build();
intersections.add(intersection);
}
public void startSystem() {
if (intersections.isEmpty()) {
System.out.println("No intersections to manage. System not starting.");
return;
}
System.out.println("--- Starting Traffic Control System ---");
executorService = Executors.newFixedThreadPool(intersections.size());
intersections.forEach(executorService::submit);
}
public void stopSystem() {
System.out.println("\n--- Shutting Down Traffic Control System ---");
intersections.forEach(IntersectionController::stop);
executorService.shutdown();
try {
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
System.out.println("All intersections stopped. System shut down.");
}
}