Java Thread sleep()

In this guide, you will learn about the Thread sleep() method in Java programming and how to use it with an example.

1. Thread sleep() Method Overview

Definition:

The Thread.sleep() method is used to pause the execution of the current thread for a specified amount of time.

This method is often used to introduce a delay or to allow CPU time for other tasks. It’s essential to note that the sleep time is not guaranteed to be precise, as it is dependent on system timers and schedulers.

Syntax:

1) public static void sleep(long millis) throws InterruptedException
2) public static void sleep(long millis, int nanos) throws InterruptedException

Parameters:

- millis: The time to sleep in milliseconds.

- nanos: Additional nanoseconds to sleep, ranging from 0 to 999999.

Key Points:

- The sleep() method is a static method that belongs to the Thread class and is used to suspend the execution of the calling thread for a specified period.

- It can throw an InterruptedException if another thread interrupts the sleeping thread.

- The actual time the thread will sleep might be slightly different due to system timers and schedulers.

- The overloaded sleep() method with nanos provides finer granularity but is rarely used in practice.

2. Thread sleep() Method Example

public class ThreadSleepExample {
    public static void main(String[] args) {
        System.out.println("Sleeping thread for 5 seconds...");

        try {
            // Pause the main thread for 5 seconds (5000 milliseconds)
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Resuming execution after sleep!");
    }
}

Output:

Sleeping thread for 5 seconds...
Resuming execution after sleep!

Explanation:

In the given example, the main thread prints "Sleeping thread for 5 seconds..." and then calls Thread.sleep(5000), which pauses its execution for 5 seconds. After the sleep duration has passed, the main thread resumes and prints "Resuming execution after sleep!".

Comments