Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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 InterruptedException

Parameters

ParameterTypeDescription
millislongThe 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.

Thanks for reading!

Donate to the site — we work hard for you.