Well, the output of this code can basically be any interleaved version of the two threads' numbers. They'll both individually print the numbers from 1 to 10 in sequence, but there is no guarantee for when this happens in relation to each other, since there's no synchronization between them, and without the delay inside the loop, they are both just trying to print the numbers as fast possible.
These are all perfectly valid outcomes for this code:
T1 1 2 3
T2 1 2 3
out 1 1 2 2 3 3
T1 1 2 3
T2 1 2 3
out 1 2 3 1 2 3
T1 1 2 3
T2 1 2 3
out 1 2 3 1 2 3
T1 1 2 3
T2 1 2 3
out 1 1 2 3 2 3
If you put the delay inside the loop, and it's long enough, you'll somewhat guarantee that you get a sequence like 1 1 2 2 3 3
, but the order in which the two copies of a number are printed between the threads is still up to how the threads happen to get scheduled in a particular run.
< ~100 ms >
T1 1 2 3
T2 1 2 3
out 11 22 33
T1 1 2 3
T2 1 2 3
out 11 22 33
T1 1 2 3
T2 1 2 3
out 11 22 33
Note that Thread.sleep
itself isn't perfectly accurate either, and using it for this purpose will just happen to work out most of the time if you put in a long enough delay here.
If you want to write multithreaded code that runs predictably, look into different synchronization methods (synchronized
, locks, semaphores, etc).