Thread.sleep() in Java with Examples

In Java, Thread.sleep() is a method that allows you to pause the execution of a thread for a specified amount of time. It’s useful when you want to delay the execution of a certain task or create a pause in a program.

The Thread.sleep() method takes one argument: the number of milliseconds to pause the thread. Here are a few examples of how you can use Thread.sleep() in Java:

Example 1: Pause the thread for one second

try {
    Thread.sleep(1000); // 1000 milliseconds = 1 second
} catch (InterruptedException e) {
    // Handle the exception if needed
}

This code will pause the current thread for one second. The try-catch block is used because Thread.sleep() can throw an InterruptedException if another thread interrupts the current thread while it’s sleeping.

Example 2: Pause the thread for a variable amount of time

int delay = 5000; // 5 seconds
try {
    Thread.sleep(delay);
} catch (InterruptedException e) {
    // Handle the exception if needed
}

This code will pause the current thread for a variable amount of time specified by the delay variable. In this case, the thread will pause for 5 seconds.

Example 3: Create a delay loop

for (int i = 0; i < 10; i++) {
    System.out.println(i);
    try {
        Thread.sleep(1000); // 1 second delay
    } catch (InterruptedException e) {
        // Handle the exception if needed
    }
}

This code will print the numbers 0 through 9 with a one-second delay between each number. The Thread.sleep() method is used inside the loop to create the delay.

Note that using Thread.sleep() to create a delay is not the most accurate method. The actual time that the thread is paused may be slightly longer or shorter than the specified time due to factors such as thread scheduling and system load.

The sleep() Method Syntax:

The sleep() method is a static method of the Thread class in Java, which is used to pause the execution of the current thread for a specified amount of time. Here is the syntax of the sleep() method:

public static void sleep(long millis) throws InterruptedException

The sleep() method takes one argument:

  • millis – The number of milliseconds to pause the thread. This must be a non-negative value.

The method throws an InterruptedException if another thread interrupts the current thread while it is sleeping. The InterruptedException is a checked exception that must be handled by the caller using a try-catch block or declared to be thrown using the throws keyword.

Here is an example of how to use the sleep() method to pause the current thread for 1 second:

try {
    Thread.sleep(1000); // pause for 1 second
} catch (InterruptedException e) {
    // handle the exception if needed
}

In this example, the Thread.sleep(1000) statement pauses the current thread for 1 second (1000 milliseconds). If another thread interrupts the current thread while it is sleeping, an InterruptedException will be thrown, which can be caught and handled in the catch block.

Parameters:

The sleep() method in Java takes only one parameter, which specifies the number of milliseconds for which the current thread should be paused.

Here is the syntax of the method:

public static void sleep(long millis) throws InterruptedException

The parameter millis is of type long and specifies the number of milliseconds for which the current thread should be paused. This must be a non-negative value.

For example, if you want to pause the current thread for 5 seconds, you can call the sleep() method with an argument of 5000 (5 seconds * 1000 milliseconds per second):

try {
    Thread.sleep(5000); // pause for 5 seconds
} catch (InterruptedException e) {
    // handle the exception if needed
}

In this example, the Thread.sleep(5000) statement pauses the current thread for 5 seconds (5000 milliseconds). If another thread interrupts the current thread while it is sleeping, an InterruptedException will be thrown, which can be caught and handled in the catch block.

Important Points to Remember About the Sleep() Method:

Here are some important points to remember about the sleep() method in Java:

  1. The sleep() method pauses the execution of the current thread for a specified amount of time.
  2. The argument to the sleep() method specifies the number of milliseconds for which the thread should be paused. This must be a non-negative value.
  3. The sleep() method is a static method of the Thread class, and is invoked using the class name.
  4. The sleep() method can throw an InterruptedException if another thread interrupts the current thread while it is sleeping.
  5. The InterruptedException is a checked exception, and must be handled using a try-catch block or declared to be thrown using the throws keyword.
  6. The sleep() method is not guaranteed to pause the thread for exactly the specified amount of time. The actual pause time may be slightly longer or shorter due to factors such as thread scheduling and system load.
  7. The sleep() method is often used in combination with other synchronization methods to control the execution of multiple threads in a program.

It’s important to use the sleep() method judiciously and to avoid using it to create long delays in a program, as this can cause performance issues and potentially impact the responsiveness of the program.

Example of the sleep() method in Java : on the custom thread:

Here is an example of using the sleep() method in Java on a custom thread:

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Thread " + Thread.currentThread().getName() + " is running. i = " + i);
            try {
                Thread.sleep(1000); // pause for 1 second
            } catch (InterruptedException e) {
                // handle the exception if needed
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        thread1.start();
        thread2.start();
    }
}

In this example, we create a custom thread by extending the Thread class and overriding the run() method. Inside the run() method, we use a for loop to print a message and pause the thread for 1 second using the sleep() method.

In the main() method, we create two instances of the MyThread class and start them using the start() method. This creates two separate threads that run concurrently, each executing the run() method of the MyThread class.

When we run the program, we should see output similar to the following:

Thread Thread-0 is running. i = 1
Thread Thread-1 is running. i = 1
Thread Thread-1 is running. i = 2
Thread Thread-0 is running. i = 2
Thread Thread-0 is running. i = 3
Thread Thread-1 is running. i = 3
Thread Thread-1 is running. i = 4
Thread Thread-0 is running. i = 4
Thread Thread-0 is running. i = 5
Thread Thread-1 is running. i = 5
Thread Thread-0 is running. i = 1
Thread Thread-1 is running. i = 1
Thread Thread-1 is running. i = 2
Thread Thread-0 is running. i = 2
Thread Thread-0 is running. i = 3
Thread Thread-1 is running. i = 3
Thread Thread-1 is running. i = 4
Thread Thread-0 is running. i = 4
Thread Thread-0 is running. i = 5
Thread Thread-1 is running. i = 5

As we can see, the two threads run concurrently and print their output messages in an interleaved manner. The sleep() method is used to pause each thread for 1 second between iterations of the loop.

Example of the sleep() Method in Java : on the main thread:

Here is an example of using the sleep() method in Java on the main thread:

public class Main {
    public static void main(String[] args) {
        System.out.println("Start of program.");
        try {
            Thread.sleep(5000); // pause for 5 seconds
        } catch (InterruptedException e) {
            // handle the exception if needed
        }
        System.out.println("End of program.");
    }
}

In this example, we use the sleep() method on the main thread of the program to pause for 5 seconds between printing the start and end messages.

When we run the program, we should see output similar to the following:

Start of program.
(wait for 5 seconds)
End of program.
Start of program.
(wait for 5 seconds)
End of program.

As we can see, the sleep() method causes the main thread to pause for 5 seconds before continuing with the execution of the program.

Example of the sleep() Method in Java: When the sleeping time is -ive:

The sleep() method in Java expects a non-negative value as its argument, which represents the number of milliseconds that the thread should sleep. If a negative value is passed to the sleep() method, it will throw an IllegalArgumentException.

Here is an example of using the sleep() method with a negative value:

public class Main {
    public static void main(String[] args) {
        try {
            Thread.sleep(-1000); // pause for -1 second
        } catch (InterruptedException e) {
            // handle the exception if needed
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid argument passed to sleep() method.");
        }
    }
}

In this example, we pass a negative value (-1000) to the sleep() method. This causes an IllegalArgumentException to be thrown, which we catch and handle by printing an error message.

When we run the program, we should see output similar to the following:

Invalid argument passed to sleep() method.

As we can see, passing a negative value to the sleep() method is not valid and results in an exception being thrown. It’s important to always pass a non-negative value to the sleep() method to ensure proper behavior of the program.