Sobes.tech
Middle

What are the differences between Thread.sleep() and Thread.yield() methods?

sobes.tech AI

Answer from AI

Thread.sleep() pauses the execution of the current thread for a specified time, putting it into the Timed Waiting state. It does not give CPU time to other threads. Thread.yield() informs the thread scheduler that the current thread is ready to temporarily yield execution to other threads with the same or higher priority, but there is no guarantee that it will do so. yield() transitions the thread to the Runnable state.

Main differences:

  • Duration: sleep() guarantees a pause for the specified time. yield() does not guarantee control transfer or a specific pause duration.
  • Thread state: sleep() transitions the thread to Timed Waiting (or Waiting with a timeout). yield() transitions the thread to Runnable.
  • Purpose: sleep() is used to introduce delays. yield() is used to allow other threads to execute, especially in loops, to avoid CPU monopolization.
  • Scheduler: sleep() does not affect the scheduler (except that the thread is inactive). yield() is a hint to the scheduler.

Example usage:

// Using sleep()
try {
    Thread.sleep(100); // Pause for 100 milliseconds
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}
// Using yield()
Thread.yield(); // Attempt to yield execution