I don’t understand why the threads here will not switch (they do, after a "long" and largely unpredictable time). Please give me advice on how to make this simple example of outputting ONE and TWO after each other. As before, if I switch yield () with sleep (1), it will work just as I need (despite the wait is pointless).
I think this is more due to the difference between ~ 1000 println calls per second (when using sleep(1) ) and many, and even more without sleep. I think that Thread is actually inferior, but it may be that it is on a multiprocessor box, so the yield does not actually work.
So, what you see is just the explosion of a large volume race on System.out . If you run this for a minute with the results going to a file, I think you will see a similar number of "ONE" and "TWO" messages in the output. Even if you removed yield() , you will see this behavior.
I just checked out a quick trial with code sending the output to /tmp/x . The program with yield() executed within 5 seconds, generated lines of 1.9 m / 483 thousand, With the output sort | uniq -c sort | uniq -c from:
243152 ONE 240409 TWO
This means that each stream generates more than 40,000 lines per second. Then I deleted the yield() , and I got roughly the same results with different row values, as you would expect under race conditions, but with the same order of magnitude.
source share