Threads ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-22

Thread.sleep() in Java: How to Pause a Thread

Thread.sleep() is a static method of java.lang.Thread that pauses the current thread for a given number of milliseconds. It is the standard answer to "how do I sleep (pause) in Java". The method is declared with throws InterruptedException, so you either wrap the call in try/catch or let the exception propagate. For example, Thread.sleep(1000) pauses for about one second:

try {
    Thread.sleep(1000); // pause for ~1 second
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

Note the word "current". If you have a thread object worker and write worker.sleep(5000), it is not worker that goes to sleep but the thread executing that line, usually main. The code compiles, and the bug only shows up at runtime (see Thread.sleep() is a static method).

Why put a thread to sleep

Typical reasons to call sleep():

  • The thread runs too fast — for example, you want output to appear gradually so you can actually see it.
  • You want to give other threads a chance to run: while it sleeps, the current thread doesn't compete for the CPU, and the scheduler hands time to the others. sleep() can't switch to one particular thread, though.
  • You need to simulate a long-running operation in a demo, or wait between retry attempts.

Thread.sleep() Syntax and Overloads

Thread.sleep() has three overloads: sleep(long millis), sleep(long millis, int nanos) and sleep(Duration duration), added in Java 19. All of them are static and all throw InterruptedException. Another popular way to pause is TimeUnit.SECONDS.sleep(1), which calls the same Thread.sleep() under the hood.

Call What it does Edge cases
Thread.sleep(long millis) Pauses for millis milliseconds Negative value → IllegalArgumentException
Thread.sleep(long millis, int nanos) Milliseconds plus nanoseconds nanos outside 0–999999 → IllegalArgumentException; no real nanosecond precision
Thread.sleep(Duration duration) Pauses for the given duration (Java 19+) Unambiguous to read: Duration.ofSeconds(2) instead of a "magic" 2000
TimeUnit.SECONDS.sleep(1) Pauses in the given unit: MILLISECONDS, SECONDS, MINUTES… A value <= 0 doesn't sleep and doesn't throw
import java.time.Duration;
import java.util.concurrent.TimeUnit;

public class SleepOverloadsExample {
    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(1000);                     // 1 second
        Thread.sleep(Duration.ofMillis(1500));  // 1.5 seconds, Java 19+
        TimeUnit.SECONDS.sleep(1);              // 1 second
        TimeUnit.MILLISECONDS.sleep(250);       // 250 ms
        System.out.println("Done");
    }
}
Done

"Done" appears after roughly 3.75 seconds. Which form to pick is a matter of readability: Thread.sleep(300000) is easy to misread, while TimeUnit.MINUTES.sleep(5) or Thread.sleep(Duration.ofMinutes(5)) is not.

If you came from Python and searched for "java time sleep" or "java system sleep": Java has no System.sleep() and no time.sleep(). A pause in Java always goes through a thread — Thread.sleep() directly or TimeUnit.X.sleep() as a wrapper around it.

Thread.sleep() Example: Three Threads with a Pause

In this example three threads run the same Runnable: each prints its name and the iteration number three times and sleeps for 1000 ms between iterations. The pause stretches the work over three seconds, so you can see the threads taking turns.

public class SleepRunnable implements Runnable {
    public void run() {
        for (int x = 1; x < 4; x++) {
            System.out.println("Run by "
                    + Thread.currentThread().getName()
                    + ", x is " + x);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt(); // restore the flag
                return;                             // and stop working
            }
        }
    }
}
public class SleepRunnableExample {
    public static void main(String[] args) {
        SleepRunnable sleepRunnable = new SleepRunnable();

        Thread one = new Thread(sleepRunnable);
        one.setName("Fred");
        Thread two = new Thread(sleepRunnable);
        two.setName("Lucy");
        Thread three = new Thread(sleepRunnable);
        three.setName("Ricky");

        one.start();
        two.start();
        three.start();
    }
}

One possible output:

Run by Fred, x is 1
Run by Ricky, x is 1
Run by Lucy, x is 1
Run by Lucy, x is 2
Run by Fred, x is 2
Run by Ricky, x is 2
Run by Fred, x is 3
Run by Lucy, x is 3
Run by Ricky, x is 3

The lines come out in groups of three, about a second apart. The order of names within a group changes from run to run: which thread wakes up first is decided by the scheduler, not by the order of the start() calls. Without sleep(), the first thread would most likely print all three lines before the others even started.

InterruptedException: Why You Need try/catch and How to Handle It

InterruptedException is a checked exception that Thread.sleep() throws when another thread calls interrupt() on the sleeping thread. The thread wakes up early, and its interrupt flag is cleared. The right way to handle it is to restore the flag with Thread.currentThread().interrupt() or rethrow the exception — never swallow it.

public class SleepInterruptExample {
    public static void main(String[] args) throws InterruptedException {
        Thread sleeper = new Thread(() -> {
            try {
                Thread.sleep(10_000);
                System.out.println("Woke up on its own");
            } catch (InterruptedException e) {
                System.out.println("Interrupted: " + e.getMessage());
                System.out.println("Interrupt flag: "
                        + Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();
                System.out.println("Flag after interrupt(): "
                        + Thread.currentThread().isInterrupted());
            }
        });
        sleeper.start();
        Thread.sleep(500);
        sleeper.interrupt(); // wake it after half a second instead of ten
        sleeper.join();
    }
}
Interrupted: sleep interrupted
Interrupt flag: false
Flag after interrupt(): true

"Woke up on its own" is never printed: the sleep is interrupted after 500 ms. The second line shows why an empty catch is dangerous. The flag is already cleared, so code further up the stack (a loop checking isInterrupted(), a thread pool, a framework) never learns that the thread was asked to stop. The e.printStackTrace() you see in many older examples is no better: the stack trace gets printed, and the thread carries on as if nothing happened.

What to put in catch depends on where the call is:

  • If the method can declare throws InterruptedException, rethrow and let the caller decide.
  • Inside run() you can't throw a checked exception, so restore the flag and finish, as in SleepRunnable above.
  • If you need to wrap it in an unchecked exception, call Thread.currentThread().interrupt() first, then throw new RuntimeException(e).

Thread.sleep() Is a Static Method: What t.sleep() Really Does

Thread.sleep() always puts to sleep the thread that called it. Calling it through a reference to another thread, t.sleep(1000), compiles (the IDE only warns about a static method accessed via an instance), but t keeps running and the current thread sleeps instead. In Java you can't put another thread to sleep "from the outside".

What does this code print?

public class StaticSleepTrap {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() ->
                System.out.println("worker: " + Thread.currentThread().getName()));
        worker.start();

        long start = System.currentTimeMillis();
        worker.sleep(2000); // actually Thread.sleep(2000) for main
        System.out.println("main woke up after ~"
                + (System.currentTimeMillis() - start) / 1000 + " s");
    }
}
worker: Thread-0
main woke up after ~2 s

worker prints its line right away and finishes, while main is the one that "sleeps" for two seconds. If you want another thread to pause, it has to call Thread.sleep() in its own code, for example when it sees a flag or receives a signal through wait()/notify().

What Happens to a Thread During sleep()

While in sleep(), a thread is in the TIMED_WAITING state, uses no CPU and does not release any monitors it holds. After waking up it becomes RUNNABLE again and waits for the scheduler to give it CPU time. TIMED_WAITING is the state of a thread waiting with a time limit; plain WAITING has no limit.

Timing isn't guaranteed. According to the documentation, the pause depends on the precision of system timers and the OS scheduler. Unless it's interrupted, a thread never wakes up early, but it can wake up noticeably late: after the timer fires it still has to wait for a CPU. That's why Thread.sleep(1000) in a loop doesn't give you exactly 60 iterations per minute — the error accumulates. For a steady rhythm, use scheduleAtFixedRate() (see below).

Thread.sleep(0) doesn't pause at all. In practice it's a hint to the scheduler, close to Thread.yield(), and its behavior depends on the JVM and OS. One useful detail: if the interrupt flag is already set, even sleep(0) throws InterruptedException.

Sleeping inside synchronized

A thread that falls asleep inside a synchronized block holds the monitor for the whole sleep. Every other thread that needs that monitor sits in the BLOCKED state, so sleep(5000) under a lock turns it into a five-second queue. Move pauses outside synchronized. Holding a lock while waiting is also one of the ingredients of a deadlock in Java: only wait() gives the monitor up while the thread waits.

sleep() vs wait() and yield(): What's the Difference

The key difference between sleep() and wait(): sleep() simply pauses for a period of time and keeps the monitor, while wait() waits for a signal from another thread and releases the object's monitor while waiting. That's why wait() can only be called inside synchronized, and sleep() can be called anywhere.

Aspect Thread.sleep() Object.wait()
Declared in Static method of Thread Instance method of Object
Monitor Kept Released while waiting
Where it can be called Anywhere Only inside synchronized on that object, otherwise IllegalMonitorStateException
When the thread wakes up Time is up or interrupt() notify()/notifyAll(), the wait(ms) timeout expires, interrupt(), or a spurious wakeup
Thread state TIMED_WAITING WAITING or TIMED_WAITING
Used for A pause of known length Waiting for an event from another thread

A typical wait()/notify() pair looks like this: one thread calls wait() in a loop until a condition becomes true, and another thread changes the condition and calls notify() or notifyAll() on the same object.

Thread.yield() differs from sleep() in that it sets no pause at all: the thread stays RUNNABLE and only hints to the scheduler that it's willing to give up the CPU. The scheduler is free to ignore that hint.

Why sleep() in a Loop Is a Bad Way to Wait for an Event

Thread.sleep() works for a pause of known length, but not for waiting on an event: "check the condition, sleep, check again" reacts late, wastes resources on empty checks, and without volatile or synchronization may never see the change at all. Java has dedicated tools for waiting.

Here's the kind of code that tends to get flagged in code review:

// Bad: polling a flag in a loop
while (!dataReady) {
    Thread.sleep(100);
}
process();

It has three problems. The reaction lags by up to 100 ms. If you shorten the pause, the thread wakes up for nothing more often. And if dataReady isn't declared volatile and isn't guarded by synchronization, the thread is allowed to never see the true written by another thread: without volatile, the JVM doesn't guarantee that a write in one thread becomes visible to another.

What to use instead:

Task Instead of sleep() in a loop
Wait for another thread to finish t.join() — blocks until thread t terminates
Wait for a signal from another thread wait()/notify(), or CountDownLatch from java.util.concurrent
Run a task periodically or after a delay ScheduledExecutorService: schedule(), scheduleAtFixedRate(), scheduleWithFixedDelay()
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TickExample {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(
                () -> System.out.println("tick"), 0, 1, TimeUnit.SECONDS);

        Thread.sleep(3500); // sleep is fine here: we just wait 3.5 s in a demo
        scheduler.shutdown();
    }
}
tick
tick
tick
tick

The task starts immediately and then repeats every second (at 0, 1, 2 and 3 seconds), so four lines are printed within 3.5 seconds. Unlike while (true) { work(); Thread.sleep(1000); }, the interval is measured from the start of each run, and the time the task itself takes doesn't shift the schedule.

Thread.sleep() in Virtual Threads (Java 21)

In a virtual thread (Java 21+), Thread.sleep() doesn't block an OS thread: the virtual thread is unmounted from its carrier thread, and the carrier runs other virtual threads while the first one sleeps. That's why thousands of sleeping virtual threads are cheap, while ten thousand platform threads calling sleep() are not.

Thread vt = Thread.ofVirtual().start(() -> {
    try {
        Thread.sleep(Duration.ofSeconds(1)); // the carrier thread is free
        System.out.println("virtual: " + Thread.currentThread().isVirtual());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
});
vt.join();
// Output: virtual: true

A version detail: in Java 21–23, a virtual thread that sleeps inside synchronized gets pinned to its carrier thread and blocks it for the whole sleep. Java 24 fixed this (JEP 491), but the advice from the tip above still applies: the monitor is held during the sleep, and other threads still wait.

Frequently Asked Questions

Can I call Thread.sleep() without try/catch?

Yes, if the method containing the call declares throws InterruptedException — for example, public static void main(String[] args) throws InterruptedException. That doesn't work inside run() of a Runnable: its signature doesn't allow checked exceptions, so try/catch is mandatory there. How to write the catch correctly is covered in InterruptedException.

Does Thread.sleep() use CPU?

No. A sleeping thread is taken off the scheduler and gets no CPU time until the pause ends. What does burn CPU is the other way to wait — an empty loop like while (System.currentTimeMillis() < end) {} (busy-waiting), which spins and occupies a whole core.

Can one thread put another thread to sleep?

No. sleep() is static and always applies to the current thread, even if you call it through a reference like otherThread.sleep(). For another thread to pause, it has to call sleep() or wait() itself — for example, after checking a flag you set. An example with output is in Thread.sleep() is a static method.

Why does IntelliJ IDEA highlight Thread.sleep() in a loop?

That's the inspection "Call to 'Thread.sleep()' in a loop, probably busy-waiting": the IDE suspects the loop is waiting for a condition to change. If you really are waiting for an event, replace polling with join(), wait()/notify(), CountDownLatch or ScheduledExecutorService — see sleep() in a loop. If the loop is a retry with a pause between attempts, you can suppress the warning.

Comments

Please log in or register to have a possibility to add comment.