Hi!
Could you please clarify why the correct answer is 000000 and not 000?
Thank you!
You see, there are three threads, and each runs the doVIP() method ones. However, the important point to note here is we start these threads only after all three threads are constructed.
Another important part is that x is a static variable. So despite how many ThreadClass objects we have, it gets the last value it was assigned to. Right?
Let's see in the constructor:
public ThreadClass(int x){ this.x=x; }
The keyword this is a trick. It appears to change x in the current object, but really x is static, so there is only one copy of x. We have these constructor invocations:
ThreadClass tc1=new ThreadClass(2); ThreadClass tc2=new ThreadClass(1); ThreadClass tc3=new ThreadClass(0);
When tc1 constructor runs, x becomes 2. When tc2 constructor runs, x is 1. When tc3 constructor runs, x is 0. That's it, we have x is 0 by now. We still not have started these threads. As we start these threads now (with the start() method), we get x as 0. That's why it always yields out 0.
As we start these threads, in the doVIP() method, we have the statement s = s + x;
When the first thread runs this, s becomes '0', and out print statement prints
0
Second thread makes s become '00', and print statement prints
00
Third statement makes s become 000 and prints
000
Combining the three prints above, we have printed 000000.
Does that sounds clear?
Yes thank you!