Java Thread sleep() Method Tutorial

In this section, we will learn what the Thread sleep() method is and how to use it in Java.

Note: we’re assuming you’re already familiar with how to create threads in Java.

What is Thread sleep() Method in Java?

The `sleep()` method in Java is a way of making a thread to wait for a period!

Basically, this method takes a value in millisecond and nanosecond and it causes the target thread to wait until that period passes.

This is especially helpful if our program is in a multithreaded environment and one thread needs the result that another thread should provide. So by sleeping for a period, one thread can let the other thread to do its work and provide the required value for the slept thread.

Another use of this sleep() method is when a thread sends a request to an external resource and it needs to wait for that resource to respond with a value. So, here if the current thread can’t proceed to run the rest of instructions until it gets the value, it can run this method and sleep for a while until the value is provided.

Thread sleep() Method Syntax:

public static void sleep(long mls) throws InterruptedException

public static void sleep(long mls, int n) throws InterruptedException

The first version of this method takes one value, and that is the time in millisecond that we want the target thread to wait and then proceed to run the rest of its instructions.

The second version of this method takes a second argument, which is a time in nanoseconds. So if we want to be more precise with the amount of time that a thread should sleep, we can use this second version of the method.

Notes:

  • The method is static. So if we want to use it, we need to use the Thread class.
  • The method throws the `InterruptedException` exception, so we need to wrap this method in a try-catch block.

Example: using Thread sleep() method in Java

public class Main {
    public static int count = 0;
    public static void main(String[] args) {
      

        Thread t1 = new Thread(Main::increment, "Thread-one");
        Thread t2 = new Thread(Main::slp, "Thread two");

        t1.start();
        t2.start();

    }
    public static void increment(){
        for (int i = 0; i<5; i++){
            try {
                Thread.sleep(1000);
                System.out.println("The current value of the count variable is: "+count++);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void slp(){
           while(count !=5){
               try {
                   Thread.sleep(1000);
                   System.out.println("The second thread sleeps for another 1 second");
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        System.out.println("The second thread is done sleeping!");
    }
}

Output:

The second thread sleeps for another 1 second

The current value of the count variable is: 0

The second thread sleeps for another 1 second

The current value of the count variable is: 1

The second thread sleeps for another 1 second

The current value of the count variable is: 2

The second thread sleeps for another 1 second

The current value of the count variable is: 3

The second thread sleeps for another 1 second

The current value of the count variable is: 4

The second thread sleeps for another 1 second

The second thread is done sleeping!

How does Thread sleep() method work in Java?

In the last example, we have two threads, `t1` and `t2`.

The first thread got the `increment()` method to run, and the second thread is in charge of running the `slp()` method.

Here, for the t1 thread, it sleeps for one second within the body of the for-loop per each iteration and then increases the value of `count` variable and moves to the next iteration of the loop. This happens for 5 times.

For the second thread `t2`, it enters a while loop and immediately sleeps for one seconds. After that, it will check the condition of the while loop to see if it’s still true or resolved to false. Here, this condition checking happens 5 times until the value of the count variable becomes equal to the value 5. So in total, the second thread also sleeps for 5 seconds and at the end after the condition of the while loop resolved to false, the thread exited the loop and finished the slp() method by sending the value of the last `println()` method to the output stream.

Java Thread sleep() Method Note:

Be aware that if a thread entered a synchronized method, and we called the `sleep()` method on that thread, the thread will sleep for the specified period, but the important part is that it won’t release the acquired lock! (Please check the Java Thread Synchronized section if you’re not familiar with the synchronization).

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies