What is the output if the main() method is run?
1. public class Starter extends Thread {
2. private int x = 2;
3. public static void main(String[] args) throws Exception {
4. new Starter().makeItSo();
5. }
6. public Starter(){
7. x = 5;
8. start();
9. }
10. public void makeItSo() throws Exception {
11. join();
12. x = x – 1;
13. System.out.println(x);
14. }
15. public void run() { x *= 2; }
16. }
A.
4
B.
5
C.
8
D.
9
E.
Compilation fails.
F.
An exception is thrown at runtime.
G.
It is impossible to determine for certain.
Explanation:
9
Correct answer is D, 9. The program launches a second thread when executes the constructor, calling start() method, and pauses the main thread, calling the method join() in the method makeItSo(); then, the second thread continue with its execution leaving the attribute ‘x’ with the value 10, in the method run(), and finish; in that moment, main thread continues, and decreases the attribute in 1, leaving it with value 9.