The given answer for the java code is �11� or �12�. I don�t understand the answer �12�. Pls explain to me.
Thanks, Raghu.K
class TestThread13 extends Thread{ private int i; public void run(){ i++; } public static void main(String[] args) { TestThread13 a = new TestThread13(); a.run(); System.out.print(a.i); a.start(); System.out.print(a.i); } }
If you call any order ((a.run ()/a.start ()) or (a.start ()/a.run ())) the answer should be "12". Becuase the I am going to increase by one. If it's true why the answer is "11�. Why it's not increasing the "I" on second call.
Actually there is no way to know what it is going to be printed. It could be 11 or 12.
You can say with all certainty that 1 will be printed first, because you call run() method which increments the value of i, and after that you print it. That's the only certain thing you can say your program does.
But after calling the start() method of the thread, you cannot know for sure what it is going to happen.
Calling the start() method on a thread spawns a new thread, but the order of execution is platform dependant.
It is possible that the thread's run method is executed before the main method ends, or, on the contrary, that the main method finishes before the thread has had chance to alter the value of i.
When I run your code on my Linux computer, it printed 11.
If you want to guarantee that 12 will be printed, you will have to call the join() method on the new thread you spawned from the main thread.
I hope this helps! [ May 01, 2006: Message edited by: Edwin Dalorzo ]