Introduction
The Java Thread.sleep() method can be used to pause the execution of the current thread for a specified time in milliseconds. The argument value for milliseconds cannot be negative. Otherwise, it throws IllegalArgumentException.
sleep(long millis, int nanos) is another method that can be used to pause the execution of the current thread for a specified number of milliseconds and nanoseconds. The allowed nanosecond values are between 0 and 999999.
In this article, you will learn about Java’s Thread.sleep().
How Thread.sleep Works
Thread.sleep() interacts with the thread scheduler to put the current thread in a wait state for a specified period of time. Once the wait time is over, the thread state is changed to a runnable state and waits for the CPU for further execution. The actual time that the current thread sleeps depends on the thread scheduler that is part of the operating system.
Java Thread.sleep important points
- It always pauses the current thread execution.
- The actual time the thread sleeps before waking up and starting execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time, but for a busy system, it will be a little bit longer.
- Thread.sleep() doesn’t lose any monitors or lock the current thread it has acquired.
- Any other thread can interrupt the current thread in sleep, and in such cases InterruptedException is thrown.
Java Thread.sleep Example
Here is an example program where Thread.sleep() is used to pause the main thread execution for 2 seconds (2000 milliseconds):
ThreadSleep.java
package com.journaldev.threads;
public class ThreadSleep {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(2000);
System.out.println("Sleep time in ms = " + (System.currentTimeMillis() - start));
}
}
Output
Sleep time in ms = 2005
Notice that this difference is not precisely 2000 milliseconds. This is due to how Thread.sleep() works and the operating system-specific implementation of the thread scheduler.
Conclusion
In this article, you learned about Java’s Thread.sleep().