Java Thread Sleep
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
| Form | Example | Best 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, heremain, 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))andTimeUnit.SECONDS.sleep(1)say clearly what they mean, with no mental arithmetic.TimeUnitalso hasMICROSECONDS,MINUTES,HOURSandDAYS.Durationis 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
reminderthread is in theTIMED_WAITINGstate, as explained in Java Thread States. - After 500 ms,
maincallsreminder.interrupt(). The sleep ends at once withInterruptedException, so the 10-second wait never completes. - When
sleep()throws, it clears the thread's interrupted flag. That is whyisInterrupted()printsfalseinside thecatchblock.
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 withThread.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 withThread.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:
writertakesreportLockand then sleeps for one second without letting go of it.readerreachessynchronized (reportLock)and isBLOCKEDuntilwriterleaves the block.- This is different from
wait(), which does release the lock while waiting.
Thread.sleep() | Object.wait() | |
|---|---|---|
| Defined in | Thread (static) | Object (instance) |
| Must hold a lock | No | Yes, inside synchronized |
| Releases the lock | No | Yes |
| Wakes up when | Time is up or interrupted | Notified, time is up, or interrupted |
| Typical use | Pause or delay | Wait 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:
maincallsThread.sleep(500), somainpauses, whileworkerruns freely.- Writing
worker.sleep(500)would compile (with a warning) but would still pausemain, which is misleading. Always call it asThread.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"). Usejoin(), 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:
- Simulated failures.
chargeCard()throws for the first three calls, like a gateway that is briefly overloaded. - Growing delay. After each failure, the code sleeps with
Thread.sleep(Duration)and doubles the delay: 200, 400, 800 ms, capped atmaxDelay(2 seconds). - Jitter.
ThreadLocalRandomadds 0–49 ms of random extra wait, spreading out retries from many clients. - Giving up. If all
maxAttemptsfail, the method throws an exception that wraps the last error, using exception chaining. - Interrupt-friendly.
chargeWithRetry()declaresthrows InterruptedException, so a caller that interrupts the thread stops the retry loop immediately instead of waiting out the backoff.