Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk5 min

Java Thread.sleep() Method: Syntax and Examples

A practical guide to Java Thread.sleep(): overloads, runnable examples, interruption, lock behavior, timing limits, and common errors.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Thread.sleep() pauses the thread that calls it for a requested duration. It is useful for simple pacing, but it does not guarantee an exact wake-up time, release a monitor, or make shared data safe. Every overload can throw InterruptedException, so handle interruption as a cancellation signal rather than ignoring it.

What Thread.sleep() does

sleep() is a static method of java.lang.Thread. Calling it pauses the currently executing thread; it does not pause all threads in the application. The requested duration is a minimum delay request, not a deadline: timer precision and thread scheduling affect when execution resumes, which may be later.

Use it for a deliberate pause between actions, such as pacing a simple demonstration. Do not use it to wait for another thread to change a condition or to meet a precise timing deadline.

Syntax and Java version support

The Java SE 26 API documents these overloads:

  • Thread.sleep(long millis)
  • Thread.sleep(long millis, int nanos)
  • Thread.sleep(Duration duration)

All declare InterruptedException. The Duration overload has been available since Java 19. If your code must compile on earlier Java versions, use one of the numeric overloads. See Oracle’s Thread API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Numeric arguments

For sleep(long millis, int nanos), millis must be nonnegative and nanos must be from 0 through 999999, inclusive. Invalid values cause IllegalArgumentException. The one-argument overload likewise rejects a negative millisecond value.

Duration argument

A negative Duration is documented as a no-op. This differs from the numeric overloads’ invalid negative values, so avoid assuming that every overload handles negative input the same way.

Basic example: pause between actions

This standalone example prints three steps and requests a one-second pause after each. Save it as SleepExample.java, then compile and run it with a JDK:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
public class SleepExample {
    public static void main(String[] args) {
        try {
            for (int i = 1; i <= 3; i++) {
                System.out.println("Step " + i);
                Thread.sleep(1_000); // request a one-second pause
            }
        } catch (InterruptedException e) {
            // Preserve the cancellation signal for code higher in the call stack.
            Thread.currentThread().interrupt();
            return;
        }
    }
}

The sleep applies to the thread running main. The underscore in 1_000 is a Java numeric-literal separator and does not change the value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using the Duration overload (Java 19 and later)

For code targeting Java 19 or later, a Duration can make the time unit explicit:

import java.time.Duration;

class DurationSleepExample {
    static void pause() throws InterruptedException {
        Thread.sleep(Duration.ofMillis(250));
    }
}

Choose a duration that expresses the intended delay. The overload does not provide more precise scheduling guarantees than the numeric forms.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Handle InterruptedException deliberately

Interruption is a cooperative request that a thread stop or cancel its current work. If a sleeping thread is interrupted, sleep() throws InterruptedException and clears that thread’s interrupted status. Do not silently swallow the exception and continue as if nothing happened.

Propagate cancellation

If the calling method can declare the exception, let it propagate so the caller can decide how to stop or clean up:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
static void waitBriefly() throws InterruptedException {
    Thread.sleep(500);
}

Restore the status when handling locally

If your method cannot propagate InterruptedException, restore the interrupted status before returning or otherwise handling cancellation:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
try {
    Thread.sleep(500);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    return;
}

Restoring the status preserves the cancellation signal for code higher in the call stack. Whether to return, clean up, or take another action depends on the surrounding method’s responsibilities.

Does Thread.sleep() release a lock?

No. Sleeping does not release ownership of any monitors held by the current thread. If a thread sleeps inside a synchronized block, another thread that needs the same monitor must wait until the sleeping thread exits that block. Avoid sleeping inside a synchronized section when another thread needs the monitor to make progress. Oracle states in the Thread API that the thread “does not lose ownership of any monitors.”

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Sleep does not provide synchronization or visibility

Thread.sleep() has no synchronization semantics. A sleeping thread does not gain a reliable view of another thread’s updates simply because time passed. In particular, a loop that repeatedly reads a shared, non-volatile flag and sleeps is not made correct by the sleep call: the compiler and runtime are not required to treat sleep as a memory-visibility boundary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Use an appropriate coordination mechanism for shared state, such as a volatile field when its semantics are sufficient, a lock, or a higher-level concurrency mechanism. The Java Language Specification, Chapter 17 explains the memory model and states that sleep and yield have no synchronization semantics.

When to use another waiting mechanism

Use sleep() when the goal is simply to pause the current thread for an elapsed-time interval. If the goal is to wait for a condition, another thread, or a coordination event, use a mechanism designed for that purpose rather than polling with sleeps. Oracle’s concurrency tutorial introduces sleep as a pause mechanism; the API separately documents mechanisms such as wait() and join().

Common errors and fixes

Symptom Cause What to do
Compilation error: unreported InterruptedException The exception is checked and is not caught or declared. Declare throws InterruptedException if the caller should handle cancellation, or catch it and handle interruption deliberately.
IllegalArgumentException A numeric overload received a negative millisecond value or an out-of-range nanosecond value. Validate the input; use nonnegative milliseconds and nanoseconds from 0 to 999999.
Code wakes later than requested The requested time is not an exact wake-up guarantee; timer and scheduler precision affect resumption. Do not use sleep for a precise deadline. Design timing-sensitive work around an appropriate scheduling or timing mechanism.
Another thread appears stuck while this thread sleeps The sleeping thread may still hold a monitor needed by the other thread. Keep blocking pauses outside synchronized sections when other work needs the same monitor.
A flag change is not noticed in a sleep loop Sleep does not provide synchronization or memory visibility. Protect the shared state with suitable synchronization or use a purpose-built coordination mechanism.
Interrupted work continues unexpectedly The InterruptedException was ignored or the status was not restored when handled locally. Propagate the exception or restore the interrupt status and follow the method’s cancellation path.

Or skip the browser setup

For a website screenshot rather than a Java thread pause, ScreenshotNeo is a screenshot API and MCP server. One GET request can return an image or PDF; its API and options are documented at ScreenshotNeo docs.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of these steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Sign up for 1,000 free screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.