Java Thread sleep() Method

The Thread.sleep() method in Java is used to pause the execution of the currently executing thread for a specified period.

Table of Contents

  1. Introduction
  2. sleep() Method Syntax
  3. Understanding sleep()
  4. Examples
    • Basic Usage with sleep(long millis)
    • Using sleep(long millis, int nanos)
    • Using sleep(Duration duration)
  5. Real-World Use Case
  6. Conclusion

Introduction

The Thread.sleep() method causes the currently executing thread to pause its execution for a specified duration. This is useful for managing thread execution and simulating delays in a program.

sleep() Method Syntax

There are three overloaded versions of the sleep() method:

sleep(long millis)

public static void sleep(long millis) throws InterruptedException

Causes the currently executing thread to sleep for the specified number of milliseconds.

sleep(long millis, int nanos)

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

Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.

sleep(Duration duration)

public static void sleep(Duration duration) throws InterruptedException

Causes the currently executing thread to sleep for the specified duration.

Parameters:

  • millis: The length of time to sleep in milliseconds.
  • nanos: 0-999999 additional nanoseconds to sleep.
  • duration: The duration to sleep.

Throws:

  • InterruptedException if any thread has interrupted the current thread.

Understanding sleep()

The Thread.sleep() method pauses the current thread for the specified time. The actual sleep time may be longer due to thread scheduling delays or shorter if the thread is interrupted.

Examples

Basic Usage with sleep(long millis)

To demonstrate the basic usage of sleep(long millis), we will create a thread that sleeps for a specified time.

Example

public class SleepExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is going to sleep for 2 seconds...");
            try {
                Thread.sleep(2000); // Sleep for 2 seconds
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("Thread has woken up.");
        });

        thread.start();

        try {
            thread.join(); // Wait for the thread to finish
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after thread completion.");
    }
}

Output:

Thread is going to sleep for 2 seconds...
Thread has woken up.
Main thread resumes after thread completion.

Using sleep(long millis, int nanos)

To demonstrate the usage of sleep(long millis, int nanos), we will create a thread that sleeps for a specified time including nanoseconds.

Example

public class SleepMillisNanosExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is going to sleep for 2 seconds and 500000 nanoseconds...");
            try {
                Thread.sleep(2000, 500000); // Sleep for 2 seconds and 500000 nanoseconds
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("Thread has woken up.");
        });

        thread.start();

        try {
            thread.join(); // Wait for the thread to finish
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after thread completion.");
    }
}

Output:

Thread is going to sleep for 2 seconds and 500000 nanoseconds...
Thread has woken up.
Main thread resumes after thread completion.

Using sleep(Duration duration)

To demonstrate the usage of sleep(Duration duration), we will create a thread that sleeps for a specified duration using the Duration class.

Example

import java.time.Duration;

public class SleepDurationExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is going to sleep for 3 seconds...");
            try {
                Thread.sleep(Duration.ofSeconds(3)); // Sleep for 3 seconds
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("Thread has woken up.");
        });

        thread.start();

        try {
            thread.join(); // Wait for the thread to finish
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after thread completion.");
    }
}

Output:

Thread is going to sleep for 3 seconds...
Thread has woken up.
Main thread resumes after thread completion.

Real-World Use Case

Simulating Delays

In real-world scenarios, the Thread.sleep() method can be used to simulate delays, such as waiting for resources, simulating network latency, or pacing the execution of a program.

Example

public class DelayedTaskExample {
    public static void main(String[] args) {
        Runnable task = () -> {
            System.out.println("Starting a time-consuming task...");
            try {
                Thread.sleep(5000); // Simulate a 5-second task
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("Task completed.");
        };

        Thread thread = new Thread(task);
        thread.start();

        try {
            thread.join(); // Wait for the task to complete
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after task completion.");
    }
}

Output:

Starting a time-consuming task...
Task completed.
Main thread resumes after task completion.

Conclusion

The Thread.sleep() method in Java provides a way to pause the execution of the current thread for a specified period. By understanding how to use this method and its overloaded versions, you can manage thread execution effectively and simulate delays in your Java applications. Whether you are working with single-threaded or multi-threaded environments, the sleep() method offers a valuable tool for controlling thread behavior and timing.

Comments