The Airplane always needs to check with the Airport to see if it has an available runway before it's able to take off or land. Simulate the abovementioned scenario using multi-threading.
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
private static AtomicInteger flightNumber = new AtomicInteger(0);
private static volatile boolean runwayAvailable = true;
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
int number = flightNumber.getAndIncrement();
while (true) {
if (runwayAvailable) {
runwayAvailable = false;
try {
Thread.sleep(new Random().nextInt(3500) + 1500);
} catch (InterruptedException e) {
}
System.out.println(number + (new Random().nextBoolean() ? " the plane has landed" : " the plane took off"));
runwayAvailable = true;
break;
}
}
}).start();
}
}
}
Comments
Leave a comment