Java Thread Sleep

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 186 of 306

Java thread sleep with Thread.sleep() pauses the thread that calls it for a given amount of time. While it sleeps, the thread uses no CPU, and when the time is up it continues with the next statement.

You use it to wait between retries, to poll something at a fixed rate, to slow down a demo, or to simulate slow work such as a network call. This lesson covers every way to call Thread.sleep(), how to handle InterruptedException, and what sleeping does (and does not do) to locks.


Java Thread Sleep Syntax

sleep() is a static method of the Thread class. It has three forms, and TimeUnit offers a fourth, more readable one.

Thread.sleep(long millis)                  // pause for millis milliseconds
Thread.sleep(long millis, int nanos)       // milliseconds plus 0–999999 nanoseconds
Thread.sleep(Duration duration)            // java.time.Duration (Java 19 and later)
TimeUnit.SECONDS.sleep(long timeout)       // java.util.concurrent.TimeUnit
FormExampleBest for
sleep(millis)Thread.sleep(1500)Short, simple pauses
sleep(millis, nanos)Thread.sleep(0, 500_000)Rare; sub-millisecond requests
sleep(Duration)Thread.sleep(Duration.ofSeconds(2))Code that already works with java.time
TimeUnit.X.sleep(n)TimeUnit.MINUTES.sleep(1)Readable code with larger units

All forms throw the checked exception InterruptedException, so you must either catch it or declare it with throws. A negative time throws IllegalArgumentException.


How to Use Thread.sleep() in Java

The simplest use is to pause main between two steps. Here main declares throws InterruptedException, so no try/catch is needed.

public class SleepBasics {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Step 1: placing order");

        long start = System.currentTimeMillis();
        Thread.sleep(1500); // pause the current thread for 1.5 seconds
        long elapsed = System.currentTimeMillis() - start;

        System.out.println("Step 2: order confirmed");
        System.out.println("Paused for at least 1500 ms: " + (elapsed >= 1500));
    }
}

Output:

Step 1: placing order
Step 2: order confirmed
Paused for at least 1500 ms: true

How it works:

  • Thread.sleep(1500) pauses the current thread, here main, for 1.5 seconds.
  • System.currentTimeMillis() before and after shows how long the pause really took.
  • After the pause, the program continues exactly where it left off.

Using Java Thread.sleep() in a Loop

Calling sleep() inside a loop gives you a simple timer: do something, wait, repeat.

public class Countdown {
    public static void main(String[] args) throws InterruptedException {
        for (int secondsLeft = 5; secondsLeft > 0; secondsLeft--) {
            System.out.println("Launching in " + secondsLeft + "...");
            Thread.sleep(1000); // wait one second between lines
        }
        System.out.println("Launch!");
    }
}

Output (one line per second):

Launching in 5...
Launching in 4...
Launching in 3...
Launching in 2...
Launching in 1...
Launch!

How it works:

  • Each loop iteration prints one line and then sleeps for 1000 ms.
  • The whole program takes about five seconds.

Note: A sleep-based loop drifts a little over time, because the work inside the loop also takes time. For exact repeating schedules, use a ScheduledExecutorService, covered in the Executor Service lesson.


Sleep with Duration and TimeUnit

Numbers like 90000 are hard to read. Duration (Java 19+) and TimeUnit let you state the unit directly.

import java.time.Duration;
import java.util.concurrent.TimeUnit;

public class SleepVariants {
    public static void main(String[] args) throws InterruptedException {
        long t0 = System.nanoTime();

        Thread.sleep(200);                        // milliseconds
        Thread.sleep(0, 500_000);                 // milliseconds + nanoseconds (0.5 ms)
        Thread.sleep(Duration.ofMillis(300));     // java.time.Duration (Java 19+)
        TimeUnit.MILLISECONDS.sleep(100);         // readable unit-based sleep
        TimeUnit.SECONDS.sleep(1);                // one full second

        long totalMillis = (System.nanoTime() - t0) / 1_000_000;
        System.out.println("Total pause: at least 1600 ms -> " + (totalMillis >= 1600));
    }
}

Output:

Total pause: at least 1600 ms -> true

How it works:

  • The five calls pause for 200 ms + 0.5 ms + 300 ms + 100 ms + 1000 ms.
  • Thread.sleep(Duration.ofMillis(300)) and TimeUnit.SECONDS.sleep(1) say clearly what they mean, with no mental arithmetic.
  • TimeUnit also has MICROSECONDS, MINUTES, HOURS and DAYS. Duration is the same class used for date and time arithmetic in the Duration Class lesson.

Handling InterruptedException in Java Sleep

Another thread can wake a sleeping thread early by calling interrupt() on it. The sleeping thread then leaves sleep() immediately with an InterruptedException. This is the standard way to ask a thread to stop waiting.

public class InterruptSleep {
    public static void main(String[] args) throws InterruptedException {
        Thread reminder = new Thread(() -> {
            System.out.println("reminder: sleeping for 10 seconds");
            try {
                Thread.sleep(10_000);
                System.out.println("reminder: woke up normally");
            } catch (InterruptedException e) {
                System.out.println("reminder: interrupted, stopping early");
                System.out.println("reminder: interrupted flag now = "
                        + Thread.currentThread().isInterrupted());
            }
        }, "reminder");

        reminder.start();
        Thread.sleep(500);
        System.out.println("main: state of reminder = " + reminder.getState());
        reminder.interrupt(); // wake the sleeping thread
        reminder.join();
        System.out.println("main: reminder finished");
    }
}

Output:

reminder: sleeping for 10 seconds
main: state of reminder = TIMED_WAITING
reminder: interrupted, stopping early
reminder: interrupted flag now = false
main: reminder finished

How it works:

  • While sleeping, the reminder thread is in the TIMED_WAITING state, as explained in Java Thread States.
  • After 500 ms, main calls reminder.interrupt(). The sleep ends at once with InterruptedException, so the 10-second wait never completes.
  • When sleep() throws, it clears the thread's interrupted flag. That is why isInterrupted() prints false inside the catch block.

Restore the Interrupt Flag When You Cannot Rethrow

Inside a Runnable (see Java Runnable Interface) or a helper method you often cannot add throws InterruptedException, because run() does not declare any checked exceptions. In that case, catch it and call Thread.currentThread().interrupt() to set the flag again, so the rest of your code still knows a stop was requested.

public class RestoreInterrupt {
    static void pauseQuietly(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            // Put the flag back so callers can still see the interrupt
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread poller = new Thread(() -> {
            int round = 0;
            while (!Thread.currentThread().isInterrupted()) {
                round++;
                System.out.println("poller: checking inbox, round " + round);
                pauseQuietly(300);
            }
            System.out.println("poller: stop requested, exiting loop");
        }, "poller");

        poller.start();
        Thread.sleep(1000);
        poller.interrupt();
        poller.join();
    }
}

Output:

poller: checking inbox, round 1
poller: checking inbox, round 2
poller: checking inbox, round 3
poller: checking inbox, round 4
poller: stop requested, exiting loop

How it works:

  • pauseQuietly() hides the checked exception, but restores the flag with Thread.currentThread().interrupt().
  • The loop condition !Thread.currentThread().isInterrupted() sees the restored flag and ends the loop.
  • Without that one line, the flag would stay cleared and the poller would keep running forever.

Note: Never leave the catch (InterruptedException e) block empty. Either rethrow the exception, stop the work, or restore the flag with Thread.currentThread().interrupt().


Thread.sleep() Does Not Release Locks

A thread that sleeps inside a synchronized block keeps the lock for the whole sleep. Every other thread that needs the same lock must wait.

public class SleepKeepsLock {
    private static final Object reportLock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread writer = new Thread(() -> {
            synchronized (reportLock) {
                System.out.println("writer: got the lock, sleeping 1 second");
                try {
                    Thread.sleep(1000); // the lock is NOT released while sleeping
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                System.out.println("writer: done, releasing the lock");
            }
        }, "writer");

        Thread reader = new Thread(() -> {
            synchronized (reportLock) {
                System.out.println("reader: finally got the lock");
            }
        }, "reader");

        writer.start();
        Thread.sleep(100);
        reader.start();
        Thread.sleep(200);
        System.out.println("main: writer is " + writer.getState() + ", reader is " + reader.getState());
        writer.join();
        reader.join();
    }
}

Output:

writer: got the lock, sleeping 1 second
main: writer is TIMED_WAITING, reader is BLOCKED
writer: done, releasing the lock
reader: finally got the lock

How it works:

  • writer takes reportLock and then sleeps for one second without letting go of it.
  • reader reaches synchronized (reportLock) and is BLOCKED until writer leaves the block.
  • This is different from wait(), which does release the lock while waiting.
Thread.sleep()Object.wait()
Defined inThread (static)Object (instance)
Must hold a lockNoYes, inside synchronized
Releases the lockNoYes
Wakes up whenTime is up or interruptedNotified, time is up, or interrupted
Typical usePause or delayWait for a condition set by another thread

Thread.sleep() Always Pauses the Current Thread

Because sleep() is static, it always affects the thread that calls it. You cannot put another thread to sleep from the outside.

public class StaticSleep {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                System.out.println("worker: step " + i);
            }
        }, "worker");

        worker.start();
        // Looks like it pauses "worker", but sleep() is static:
        // it always pauses the thread that CALLS it, here: main
        Thread.sleep(500);
        System.out.println("main: I was the one sleeping");
        worker.join();
    }
}

Output:

worker: step 1
worker: step 2
worker: step 3
main: I was the one sleeping

How it works:

  • main calls Thread.sleep(500), so main pauses, while worker runs freely.
  • Writing worker.sleep(500) would compile (with a warning) but would still pause main, which is misleading. Always call it as Thread.sleep(...).

How Accurate Is Java Thread.sleep()?

sleep() guarantees that the thread pauses for at least the requested time, never less (unless interrupted). It can take a little longer, because the operating system has to schedule the thread again.

public class SleepAccuracy {
    public static void main(String[] args) throws InterruptedException {
        long[] requests = {1, 10, 50, 100};
        for (long requested : requests) {
            long start = System.nanoTime();
            Thread.sleep(requested);
            double actual = (System.nanoTime() - start) / 1_000_000.0;
            System.out.printf("requested %3d ms -> slept %.2f ms (at least requested: %b)%n",
                    requested, actual, actual >= requested);
        }
    }
}

Output (exact values differ on every machine and run):

requested   1 ms -> slept 1.26 ms (at least requested: true)
requested  10 ms -> slept 10.14 ms (at least requested: true)
requested  50 ms -> slept 50.17 ms (at least requested: true)
requested 100 ms -> slept 100.18 ms (at least requested: true)

How it works:

  • System.nanoTime() measures elapsed time precisely, so it is the right tool for timing.
  • Every sleep is slightly longer than requested. On a busy system, or on some operating systems, the extra time can be several milliseconds.

Note: Do not use sleep() to coordinate threads ("wait 100 ms and hope the other thread is done"). Use join(), covered in Java Thread Join, or other synchronization tools instead.


Real-World Example: Retry a Payment with Exponential Backoff

Network calls fail now and then. A common pattern is to retry with a growing pause between attempts (exponential backoff), plus a small random "jitter" so that many clients do not retry at the same instant.

import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

public class RetryWithBackoff {
    private static int attemptsSoFar = 0;

    // Simulated payment gateway: fails the first three calls
    static String chargeCard(String orderId, double amount) {
        attemptsSoFar++;
        if (attemptsSoFar <= 3) {
            throw new IllegalStateException("gateway timeout");
        }
        return "PAY-" + orderId + "-OK";
    }

    static String chargeWithRetry(String orderId, double amount, int maxAttempts)
            throws InterruptedException {
        Duration delay = Duration.ofMillis(200);       // first wait
        Duration maxDelay = Duration.ofSeconds(2);     // never wait longer than this

        for (int attempt = 1; attempt <= maxAttempts; attempt++) {
            try {
                String receipt = chargeCard(orderId, amount);
                System.out.println("attempt " + attempt + ": success -> " + receipt);
                return receipt;
            } catch (IllegalStateException e) {
                if (attempt == maxAttempts) {
                    throw new IllegalStateException("giving up after " + attempt + " attempts", e);
                }
                // Add a little random "jitter" so many clients don't retry at the same moment
                long jitter = ThreadLocalRandom.current().nextLong(0, 50);
                Duration wait = delay.plusMillis(jitter);
                System.out.printf("attempt %d: %s, retrying in ~%d ms%n",
                        attempt, e.getMessage(), delay.toMillis());
                Thread.sleep(wait);

                // Double the delay for the next round, up to maxDelay
                delay = delay.multipliedBy(2);
                if (delay.compareTo(maxDelay) > 0) {
                    delay = maxDelay;
                }
            }
        }
        throw new AssertionError("unreachable");
    }

    public static void main(String[] args) throws InterruptedException {
        long start = System.nanoTime();
        String receipt = chargeWithRetry("A1001", 49.99, 5);
        long totalMillis = (System.nanoTime() - start) / 1_000_000;
        System.out.println("Receipt: " + receipt);
        System.out.println("Waited at least 1400 ms in total: " + (totalMillis >= 1400));
    }
}

Output:

attempt 1: gateway timeout, retrying in ~200 ms
attempt 2: gateway timeout, retrying in ~400 ms
attempt 3: gateway timeout, retrying in ~800 ms
attempt 4: success -> PAY-A1001-OK
Receipt: PAY-A1001-OK
Waited at least 1400 ms in total: true

How it works:

  1. Simulated failures. chargeCard() throws for the first three calls, like a gateway that is briefly overloaded.
  2. Growing delay. After each failure, the code sleeps with Thread.sleep(Duration) and doubles the delay: 200, 400, 800 ms, capped at maxDelay (2 seconds).
  3. Jitter. ThreadLocalRandom adds 0–49 ms of random extra wait, spreading out retries from many clients.
  4. Giving up. If all maxAttempts fail, the method throws an exception that wraps the last error, using exception chaining.
  5. Interrupt-friendly. chargeWithRetry() declares throws InterruptedException, so a caller that interrupts the thread stops the retry loop immediately instead of waiting out the backoff.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Thread Sleep and get answers drawn from it.

Signed-in readers only.