Course contentsShow
← Java
Lesson 2591 of 2,87048. Concurrency FundamentalsFree lesson

Thread.sleep Syntax and Time Units

Using Thread.sleep with milliseconds and nanoseconds parameters to control pause duration.

Thread.sleep Syntax and Time Units

What you'll learn: How to use Thread.sleep() with different time unit parameters to precisely control how long a thread pauses.

Understanding Thread.sleep Syntax

The Thread.sleep() method comes in two overloaded forms, both accepting time parameters that tell the JVM exactly how long to pause the current thread.

The Two Forms of Thread.sleep

Millisecond-based sleep:

Thread.sleep(long millis)

This pauses the thread for the specified number of milliseconds. For example, Thread.sleep(1000) pauses for 1 second (1000 milliseconds).

Millisecond + Nanosecond precision:

Thread.sleep(long millis, int nanos)

This version allows finer control by adding nanoseconds (0-999,999) to the millisecond value. For instance, Thread.sleep(1000, 500000) pauses for 1 second plus 500,000 nanoseconds (1.0005 seconds total).

Practical Usage

try {
    // Sleep for 2 seconds
    Thread.sleep(2000);
    
    // Sleep for 1.5 seconds with nanosecond precision
    Thread.sleep(1500, 0);
    
    // Sleep for 100ms + 250,000ns = 100.00025 seconds
    Thread.sleep(100, 250000);
} catch (InterruptedException e) {
    // Handle interruption
}

Important Notes

  • The nanosecond parameter must be between 0 and 999,999
  • Actual sleep precision depends on system timer resolution—nanosecond precision may not be truly achievable on all platforms
  • Both forms throw InterruptedException and must be wrapped in try-catch

Key Takeaway: Thread.sleep() accepts either milliseconds alone or milliseconds plus nanoseconds for fine-grained control over thread pause duration, though actual precision is platform-dependent.