Answer to Question #238048 in Java | JSP | JSF for Manohar

Question #238048

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.


1
Expert's answer
2021-09-16T18:08:40-0400
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();
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS