World : 0 Hello : 0 World : 1 HEllo : 2 World : 3 Hello : 4
I am not getting how come the value of i is 0 for two times...it's a static variable so if suppose Thread t2 got access to it first (as we can see in the o/p, it's printing World 0) then after it when the access goes to Thread t2, it should print the value of i as 1...
Also, the explaination of this question says that "in total only 5 words will be printed." whereas these are 6. Can anybody explain it to me...Thanks
[Andrew: put code between [code] and [/code] UBB tags] [ June 24, 2006: Message edited by: Andrew Monkhouse ]
The results are unpredicted. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. Also, how long a thread run (time-slicing) before switching to another thread also depends on OS.
In your case, thread t1 print �Hello : 0� before thread t2 runs �i++� statement.
Enthuware Software Support
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(.... statement
Lines 34 - 42 is the increment of i
Line 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?
[Andrew: Removed some incorrect statements] [ July 01, 2006: Message edited by: Andrew Monkhouse ]