Thread.sleep()
Pauses the current thread for a given time.
Available since: Java 1.0
Syntax
public static void sleep(long millis) throws InterruptedException
public static void sleep(Duration duration) throws InterruptedExceptionParameters
| Parameter | Type | Description |
|---|---|---|
| millis | long | The pause in milliseconds (or a `Duration` since Java 19). |
Examples
A pause between steps:
void main() throws InterruptedException {
for (int i = 3; i >= 1; i--) {
IO.println(i + "...");
Thread.sleep(Duration.ofMillis(300));
}
IO.println("Go!");
}Output:
3...
2...
1...
Go!Notes
The pause is a minimum: the thread may wake up a little later. A sleeping thread can be interrupted, which throws InterruptedException. Do not use sleep() to wait for another thread — use join(), Future.get() or CountDownLatch for that.
See also
- Thread.join() — Waits for a thread to finish.
- InterruptedException — A checked exception: a waiting thread was asked to stop.
- Thread — A thread of execution that lets a program do several things at once.
Related recipes
In the tutorial
- Threads — Threads in Java — the Thread class, starting with start, waiting with join, Thread.sleep, thread names and unpredictable execution order.