Wow I didn't think my short comment would generate so much discussion.
What sleep(0) does is allow the scheduler to perform a context switch if it's needed. The scheduler checks to see if there are any threads in the 'waiting' queue, if there isone, a context switch occurs and the current thread ends up being swapped out (that is, it yields to another thread).
You can't use wait/notify is some places, an example where yield() would be required is in a routine that is doing a cpu intensive task, if this thread is preventing another thread that updates (draws) to screen, or takes input from a user, then the screen will not get refreshed nor the input get registered until the task gets completed! So it might be a good idea to call yeild() once in a while to make your app look more responsive by allowing these other (most likely lower priority) threads to get some cpu cycles.
By the way, you should never be calling yield() or sleep(0) each time through a loop, that would waste too many cpu cycles, rather it's a good idea to call these functions every once in a while.
In java sleep(0) might not be the best way to do yielding (c/c++ win32 it's the only way). I would use yield() where ever possible, sleep(0) will most likely put a running thread into a ready state while yield() will keep a thread in the running state if no other threads needs the cpu. Going from a running state to a ready state to a running state is a needless waste of time!
Originally posted by Jose Botella:
The code using sleep(0) waste time in a loop waiting for a condition to be satisfied. Have you considered using wait and notify for the thread that makes the condition true notifies the waiting thread directly, instead of being "prevented" (at impredictable times) by the check of the sleeping thread?