Recursion and Thread Scheduling
Consider the following OutOfOrderRecursion class. Which statement best describes the possible output when the main method is executed?
public class OutOfOrderRecursion {
public static void recursivePrint(int n) {
if(n <= 0){
System.out.println("Base case reached");
return;
}
new Thread(() -> recursivePrint(n - 1)).start();
System.out.println("Printing " + n);
}
public static void main(String[] args) throws InterruptedException {
recursivePrint(3);
Thread.sleep(1000);
}
}
A
The output will always display numbers in descending order followed by the base case message.
B
The output could be non-deterministic due to thread scheduling, with ‘Printing’ statements interleaved with the ‘Base case reached’ message.
C
The base case message will always be printed first, followed by numbers in ascending order.
D
The program will always result in a deadlock, so no output is produced.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE