Thread Switchng
Why?
Each thread in alive state is supposed to run in parallel to each other (from the point of view of programmer). However, it is not practical as no of cores is limited. So as many threads as supported by your processor may run in parallel. In a quad core processor, your two threads would actually run in parallel, but 10 threads won't. In order to create the illusion of parallel execution, thread switching has to take place periodically.
When?
No one can answer that. It really depends upon the JRE implementation, underlying hardware capabilities and countless other factors (like load of other running softwares). The operating system also matters a lot in this case. It is considered to be unpredictable by programmers (we should never assume or rely on the order and switching time).
How to check?
The current method that you are using to check the order of execution is misguiding. Here, a shared object
System.out
is being used, and it is cached (hopefully) by each thread and the output will be synchronized with actual memory and io at an order irrespective of the actual order of execution. It might make sense on a single core processor, but only on some implementations.
We use java to get platform independence (mostly), and this is a highly unpredictable thing which is dependent on so many parameters that we can't even list. (If you make one, it'll be outdated by next java update (probably), and it will not be same for all platforms). So I'd suggest you to assume (as far as writing programs in java is concerned) that they'll be executed in parallel.
For academic purposes, it's really an interesting topic if you are going to search and research more about it. If you find something interesting let us know too. :)
Hope this helps..
Cheers