In Java SE 22, the sleep() method is used to pause the execution of the current thread for a specified amount of time. Here's a detailed explanation of its functionality:
- Pauses Execution: When
Thread.sleep(long millis)
or Thread.sleep(long millis, int nanos)
is called, it causes the currently executing thread to sleep (temporarily cease execution) for at least the specified amount of time in milliseconds (and optionally nanoseconds).
- Interruptible: The sleep can be interrupted. If another thread calls
interrupt()
on the sleeping thread, an InterruptedException
is thrown. This allows for cooperative thread management where one thread can signal another to wake up before the sleep duration has elapsed.
- Thread State: During this sleep period, the thread transitions from the "Runnable" state to the "Timed_Waiting" state. This means it is not eligible for execution until the sleep period has ended or it is interrupted.
- Precision: The sleep time is not guaranteed to be exact. The actual time asleep might be slightly longer than requested due to system scheduling and precision limitations of the underlying operating system.
- Usage: Here's a simple example of how you might use
sleep()
in a Java program:
public class SleepExample {
public static void main(String[] args) {
try {
System.out.println("Going to sleep for 2 seconds...");
Thread.sleep(2000); // Sleep for 2000 milliseconds (2 seconds)
System.out.println("Woke up!");
} catch (InterruptedException e) {
System.out.println("Sleep interrupted!");
Thread.currentThread().interrupt(); // Re-interrupt the thread
}
}
}
- Error Handling: It's crucial to handle InterruptedException because sleep is interruptible. Re-interrupting the thread in the catch block allows whatever code caused the interruption to know that the thread was not able to complete its sleep.
This method is often used in scenarios where you want to introduce delays in thread execution, like in simulations, animations, or to implement simple rate limiting. However, for more complex timing or scheduling, consider using higher-level concurrency utilities from java.util.concurrent like ScheduledExecutorService.
The Thread.sleep() method effectively pauses the current thread for a given period of time.