Sleeping a Thread in Java

In Java, a thread can be put to sleep for a specified amount of time using the sleep() method from the Thread class. This method pauses the execution of the current thread for a defined period, allowing other threads to execute.

Key Points about Sleeping a Thread:

Syntax of sleep():

The syntax for the sleep() method is as follows:

Thread.sleep(milliseconds);

Example of Sleeping a Thread in Java:

This example demonstrates how to put a thread to sleep for 2 seconds.

Code Example

public class SleepExample extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is going to sleep.");
        try {
            Thread.sleep(2000); // Sleep for 2000 milliseconds (2 seconds)
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " was interrupted.");
        }
        System.out.println(Thread.currentThread().getName() + " has awakened.");
    }

    public static void main(String[] args) {
        SleepExample thread1 = new SleepExample();
        SleepExample thread2 = new SleepExample();

        thread1.start();
        thread2.start();
    }
}

Output:

Thread-0 is going to sleep.
Thread-1 is going to sleep.
(After 2 seconds delay)
Thread-0 has awakened.
Thread-1 has awakened.

Conclusion:

Using the sleep() method effectively allows you to control the execution flow of threads in Java. It can help manage resource usage, create delays, and improve application performance when implemented thoughtfully.