-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulationController.java
More file actions
72 lines (55 loc) · 1.93 KB
/
Copy pathSimulationController.java
File metadata and controls
72 lines (55 loc) · 1.93 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
//The siulation control
import java.util.*;
public class SimulationController {
//Kamva
private final CampusRoute campusRoute;
private final Random random = new Random();
private Thread passengerSpawner;
private volatile boolean running = false;
public SimulationController(int numStops, int numBuses) {
this.campusRoute = new CampusRoute(numStops);
for (int i = 0; i < numBuses; i++) {
Bus bus = new Bus(i + 1, campusRoute);
campusRoute.addBus(bus);
}
}
public CampusRoute getCampusRoute() {
return campusRoute;
}
public void startSimulation() {
if (running) return;
running = true;
// Start buses
for (Bus bus : campusRoute.getBuses()) {
new Thread(bus).start();
}
// spawn passenger in a separate thread
passengerSpawner = new Thread(() -> {
Random rand = new Random();
while (running) {
int numStops = campusRoute.getNumberOfStops();
int start = rand.nextInt(numStops);
int destination = (start + 1 + rand.nextInt(numStops - 1)) % numStops;
Passenger passenger = new Passenger(start, destination);
campusRoute.getStop(start).addPassenger(passenger);
Bus randomBus = campusRoute.getBuses().get(rand.nextInt(campusRoute.getBuses().size()));
randomBus.addPassenger(passenger);
// weit before spawning the next passenger
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
passengerSpawner.start();
}
public void stopSimulation() {
running = false;
if (passengerSpawner != null) {
passengerSpawner.interrupt();
}
System.out.println("Simulation stopped.");
}
}