What is the difference between sleep and yield?
Created May 4, 2012
Alex Chaffee yield() tells the JVM Thread Scheduler that it's OK to give other threads time slices. Usually the JVM uses this call to activate another thread of the same thread priority. In a good preemptive multithreading environment, yield() is a no-op. However, it is important in a cooperative multithreading environment, since without yield(), one thread can eat up all of the CPU.
sleep(x) tells the JVM Thread Scheduler to actively put this thread to sleep and not run it again until at least x milliseconds have elapsed.
Neither sleep() nor yield() change anything about the status of synchronization locks. If your thread has a lock, and you call sleep(1000), then at least a second will elapse before your thread wakes up. When it wakes up it may decide to release the lock -- or it may hold on to it longer.
See also
- What is the main difference between a preemptive scheduler and a non-preemptive scheduler?
- How does a preemptive scheduler manage a thread's timeslice?
- What is the difference between "green" threads and "native" threads?
- What is the mechanism of Thread Priority & Thread Scheduler? How do Threads with various priority levels behave in time-sliced and non-time-sliced environments?