I think that all the answers still do not make sense.
Your existing logic allows your two threads to execute simultaneously at the same time, but this is not obvious, because your numbers increase to 100, and the execution usually stays with a certain thread for more than one command at a time, otherwise when switching between the current executable thread it will be all the time too a lot of overhead. In your case, the JVM decides to run its first thread long enough so that it can print 100 numbers before "switching context" to the second thread. The JVM can choose to execute threads differently, so the result you see is not guaranteed to be the same every time.
If you increase your numbers even to 1000, you are likely to see several threads, several interleaved. You will still have large runs where one thread will produce many numbers in a row, because it is more efficient for the JVM to execute one thread for a while before switching, instead of switching the context between each instruction.
Adding Thread.sleep (1) is not a good solution when adding unnecessary delay. Of course, for 100 numbers this may not be noticeable, but for 10,000 numbers you will have a delay of 10 seconds.
Is there any reason why you need them to alternate them to a higher degree than they already do? If so, then your simple model of running two threads simultaneously is not enough. If not, just let the JVM choose the best order to start your threads (which in the simple example that you specified means that they probably won't interleave in most cases).
source share