First, note that output isn't guaranteed. You could get either of:
Notice how R2 is in their twice. That's because run() doesn't start a new thread. This means that both the first and third statements in run() are in R2 and the middle one is in R1. The reason the order changes is R1 and the final println could run in either order.
Jeanne Boyarsky wrote: The reason the order changes is R1 and the final println could run in either order.
could you please elaborate this, I didn't got the reason ?
actually I am getting the output the one I have written above (at every run), no change is there ?
for me |R2||R1b||R2| is not the issue of doubt but |R2|R2||R1b| is.... because according to the code |R2| is the first to be print !!
Puspender Tanwar wrote:actually I am getting the output the one I have written above (at every run), no change is there ?
It depends on your computer and a number of things. The point is that it isn't guaranteed. And on the exam, you have to understand what is guaranteed vs what can happen.
Puspender Tanwar wrote:could you please elaborate this, I didn't got the reason ?
Look at what runs in the foreground vs background.
1) The main method starts a thread in the background
2) There are no other threads so R2 starts running. The first thing R2 does is call run() on R1. Since run() doesn't start a new thread, this synchronously prints R2
3) Next R2 starts a new thread (R1b). Since it is being run in the background, either R1b can be printed immediately or the next line can print R2