It can be instructive to look at the byte-code generated from one of the run methods:;
General break-out:;
Lines 0 - 5 compare the value in i to see if it is past the magic number of 5 or not.Lines 7 - 31 is the System.out.println(.... statementLines 34 - 42 is the increment of iLine 42 is the end of the method. Now the bits you are interested in is that:;
At line 19
Java puts the
"World:; " into the StringBuffer (oooh, did you realize a StringBuffer was being used when you called
"World :;" + i?)
Line 22 gets the current value of
i Line 25 appends that to the StringBuffer.
Line 28 then creates a
String from that, and line 31 sends that String to the println() method.
So far so good. Now we do the increment (
i++):;
Line 34 gets the current value of
i Line 37 specifies that we are going to increment by 1.
Line 38 does the actual increment
Line 39 puts the incremented value back into
i.
Looking at all that, there is
a lot that can happen between when you retrieved a value of
i in line 22 for printing, and when you put the updated value of
i in line 39.
As Wise Owen noted, "how long a thread run (time-slicing) before switching to another thread also depends on OS." - I would add to that that it can also depend on the version of the JVM and the manufacturer of the JVM and a lot of other factors.
Originally posted by Paul Anil:;
This should be fixed.
What should be fixed?
Regards, Andrew
[Andrew: Removed some incorrect statements]
[ July 01, 2006: Message edited by: Andrew Monkhouse ]