š Rocket Launch Countdown Sync
Youāre simulating a rocket launch system.
Before the rocket can launch, it must pass several system checks (e.g., fuel, navigation, engine, weather, etc.).
Each system is checked independently by a different thread.
š Only after all checks are complete, the main launch system can proceed and say:
ā "All systems go. Launching!"
Solution Approaches
Basic Thread Join Approach
Create threads - One thread for each system check (fuel, navigation, etc.)
Start all threads - All checks run simultaneously
Wait for completion - Main thread waits until all checks finish
Launch - Only proceed if all checks were successful
public class RocketLaunchBasic {
// Task for checking individual systems
static class SystemCheck implements Runnable {
private final String systemName;
public SystemCheck(String name) {
this.systemName = name;
}
public void run() {
try {
// Simulate check time (0-2 seconds)
System.out.println("ā³ Checking " + systemName + "...");
Thread.sleep((long)(Math.random() * 2000));
System.out.println(systemName + " ā
");
} catch (InterruptedException e) {
System.out.println(systemName + " ā (Interrupted)");
}
}
}
public static void main(String[] args) throws InterruptedException {
String[] systems = {"Fuel", "Navigation", "Engine", "Weather", "Comm"};
// 1. Create threads for all systems
Thread[] threads = new Thread[systems.length];
for (int i = 0; i < systems.length; i++) {
threads[i] = new Thread(new SystemCheck(systems[i]));
}
// 2. Start all checks in parallel
System.out.println("š Starting pre-launch checks...");
for (Thread t : threads) {
t.start(); // Launch parallel execution
}
// 3. Wait for all to complete
for (Thread t : threads) {
t.join(); // Block until thread finishes
}
// 4. Final verification
System.out.println("\nš All checks completed!");
System.out.println("š All systems go. Launching!");
}
}
ā Failure Test Cases
1. Thread Never Completes (Deadlock)
One system check hangs indefinitely. Lets say one of started thread never finish its run.
public void run() {
if (systemName.equals("Fuel")) {
while(true) { /* Infinite loop */ }
}
// ... normal check ...
}
ā³ Checking Fuel...
ā³ Checking Navigation...
Navigation ā ...
(Program hangs forever)
To fix this, use join(timeout), which will only wait for specific amount of time
for (Thread t : threads) {
t.join(3000); // Wait max 3 seconds
if (t.isAlive()) {
System.out.println("ā° " + systemName + " timeout!");
t.interrupt();
}
}
2. Exception in System Check
Thread crashes during check.
public void run() {
if (systemName.equals("Navigation")) {
throw new RuntimeException("Sensor error");
}
// ... normal check ...
}
ā³ Checking Fuel...
ā³ Checking Navigation...
ā³ Checking Engine...
Exception in thread "Thread-1" java.lang.RuntimeException: Sensor error
Fuel ā
Engine āš All checks completed!
š All systems go. Launching! (ā ļø Despite failure!)
