Question 1
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) throws Exception {
List<Future<String>> fs = new ArrayList<>();
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
for (String w : new String[]{"java", "go", "kotlin"}) {
int delay = w.length() * 10;
fs.add(pool.submit(() -> { Thread.sleep(delay); return w.toUpperCase(); }));
}
}
StringBuilder sb = new StringBuilder();
for (Future<String> f : fs) sb.append(f.get()).append(' ');
System.out.println(sb.toString().trim());
}
}
- A JAVA GO KOTLIN Correct
- B GO JAVA KOTLIN
- C KOTLIN JAVA GO
- D The order varies
Correct Answer: Option A
"go" finishes first, but reading the Futures in the list's order gives submission order.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!