Hi
I have been preparing the JSCP exam and reading the book: sun certified programmer for java 6 study guide
I have a problem regarding to Chapter 9 Thread self test 15. The question is:
And given these two fragments inserted at where it says "insert code here":
I. synchronized void chat(long id){
II. void chat(long id){
which are true?
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
The default answer explaination says: "With eigher fragment, the first output must be 'yo'"
I doubt that becuase the program sets the value of static varible "flag" before the for loop and then in the for loop the value is checked and output accordingly. Is it possible that thread one invokes chat() and sets the value first but before getting into the loop thread two graps CPU and eventually gets in the loop before thread one. And as a result of that the output may starts with "dude"?
I tried the code on my PC and the result does occasionally starts with "dude". So is the default answer wrong or did I miss something?
Cheers