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 theThreadclass.- Transition to
TIMED_WAITINGstate: The thread callingsleep()enters theTIMED_WAITINGstate 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 callinginterrupt()on the sleeping thread, which throws anInterruptedException.
This allows managing thread execution and providing time for other threads.