In principle, the order in which threads are scheduled is unpredictable. So if you have two threads printing things at the same time, then it is undetermined what gets printed first.
Why did you expect the output to be "Started", "end" and then "ran"? Look at what your program is doing:
- Line 20: Creates a new
Thread
- Line 21: Starts the new Thread
- Line 22: Prints "Started"
- Line 25: Wait for 2 seconds. In the meantime, the thread is on line 12, waiting for 1 second.
- Line 17: After 1 second, the thread comes out of the waiting period and prints "ran".
- Line 31: After 2 seconds, the main thread comes out of the waiting period (from line 25) and prints "end"