You can't expect a ordered output with yield() method. yield() method gives a chance to the same priority threads to execute, but the same thread also can be chosen for executing! When you call yield on a thread, it came to Runnable state from Running state, and will compete to get the chance with other threads!
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
To see how yield can affect a way the code is executed, try the same program on different platforms with varoius number of processors,
esspecially with only one cpu/core.
Here is a simple ping-pong demo played on different "tables" that illustrates effect of yield
I ran this code first on Linux / amd cpu with 2 cores.
First with yield() commented:
Linux - 2 cores - without yield()
The second run with uncommented yield() in line 40
Linux - 2 cores - with yield()
Now let see how this program will run on Windows Xp only 1 cpu:
Win XP - 1 cpu - without yield()
Win XP - 1 cpu - with yield()
Pay attention how this program behaves on Win XP with single cpu - even when we have many threads,
a single thread without yield/sleep or wait() can grab a whole cpu time.
Unfortunately I have no Linux box with only one cpu/core.
posted 9 years ago
@Ireneusz: The PingPong example helped me understand yield() considerably better than before.