i felt the answer to be 3 but when i executed i found it is printing world 5 times..why is it so ??
Actually the answer for this is "Total 5 words will be printed." its not "WORLD" printed 5 times.Because the thread t2 and t1 starts executing simultaneously and as 'i' is static the exact value of i in both the loops interdepends.So the assured output is total five words will be printed.When you run the program you could get five "Hello" or five "World" printed that depends on the JVM to JVM. Change for loops as for(; i<10; i++) now the output on my machine is
E:\java\dev\Miss>java TestClass World World World World World World World World Hello Hello Hello
So the assured output irrespective of JVM is a total of 10 words will be printed.
First the thread t2 is started so it executes its run() version and the static variable i is used from 0 t0 4 and only then control is passed to the next thread ie t1.start().if t1's run() version has iteration say from i=0 to i<10 after excecution of run() of t2 for 5 times(i= 0 to 4),i's current value is i=5. hence now with t1.run() call the loop starts from i=5 and iterates till i<10 and prints hello,ie for i= 0 to 4 t2 prints world 5 times and for i=5 to 9 t1 prints hello 5 times thus the output will be world world world world world hello hello hello hello hello
You learn how to close your eyes and tell yourself "this just isn't really happening to me." Tiny ad: