I am a little bit confused about this question:
When fragment I or fragment II is inserted in line 4, which are true? (Choose all that apply.)
A. An exception is thrown at runtime.
B. With fragment I, compilation fails
C. With fragment II, compilation fails
D. With fragment I, the output could be: yo dude dude yo
E. With fragment I, the output could be: dude dude yo yo
F. With fragment II, the output could be: yo dude dude yo
Answers:
F is correct. With fragment I, the chat method is synchronized, so the two threads can't swap back and forth.
With either fragment, the first output must be yo.
A, B, C, D and E are incorrect based on the above.
In the book it is stated that the correct answer is F(and part of it is): With either fragment, the first output must be yo.
I have made some
test because I couldn't explain to myself why is it certain that "yo" will be the first output and received output that is in contrary: dude dude yo yo.
My assumption is that if the second fragment is used(without synchronization) it is not possible to predict the output. Am I wrong here?
If the first
thread stores its id in the flag var and right after that the second starts executing the chat method it would not print yo as a first statement.
I would be really grateful if someone can explain to me what am I missing here?
Regards