Chapter 13, p 778 (question 15)
The answer that is stated as being correct is F, but also this statement is wrong:
if chat isn't synchronized (code fragment II) it's still impossible to have the output yo dude dude yo:
Both threads have access to the flag variable but this variable is static so they have access to the same 'instance' of this variable.
Both check whether the flag is set to '0', which is it's original value (upon loading of the class).
When the first
thread (I'll call it t1) enter 'chat' (unsynchronized) execution can swap when the first thread is inside the 'if' body, the other thread (t2) can enter the method and change the value to its own id.
"yo " is outputted by t2
again swapping of threads
t1 changes the value of flag
again swap
t2 outputs "dude "
and then, in NO POSSIBLE WAY there can be another "dude " output!!!
-> the for loop in which t2 outputted "yo " and "dude " is finished, so t2 runs to the dead state
-> t1 just finished putting flag = id, so its output will be "yo " and "yo ", t2 doesn't change the value of flag anymore
so "yo dude dude yo" in answer F should be "yo dude yo yo"
kind regards,
S.