Sobes.tech
Junior

What does 'sleeping' a thread mean in Java?

sobes.tech AI

Answer from AI

Suspend the execution of the current thread for a specified period of time using the Thread.sleep() method.

// Example of using Thread.sleep
try {
    Thread.sleep(1000); // Suspend the thread for 1000 milliseconds (1 second)
} catch (InterruptedException e) {
    Thread.currentThread().interrupt(); // Restore the interrupt flag
}

Key points:

  • Thread.sleep(long millis) / Thread.sleep(long millis, int nanos): Static methods of the Thread class.
  • Transition to TIMED_WAITING state: The thread calling sleep() enters the TIMED_WAITING state and does not consume CPU time.
  • Timer granularity: Implementation depends on the operating system; sleep time is not guaranteed to be exact.
  • Does not release monitors: If the thread owns a monitor, it does not release it when calling sleep().
  • Interrupts: The sleep() method can be interrupted by calling interrupt() on the sleeping thread, which throws an InterruptedException.

This allows managing thread execution and providing time for other threads.