Thread.Sleep() – Thread Sleep() Method In Java With Examples

In this Tutorial, we will Discuss the Thread Sleep() Method in Java. We will see how does Thread.Sleep() method work with the help of Examples:

The java.lang.Thread.sleep(long millis) method is the method provided by the Thread class that puts the currently running thread to sleep. We will specify the sleep time as an argument of the sleep method.

=> Take A Look At The Java Beginners Guide Here.

Thread Sleep() method in Java

Thread Sleep() Method In Java

The Thread class of Java provides two variants of the sleep method.

The prototype of both the variants of the sleep () method is described below.

#1) Sleep Method Variant # 1

Prototype: public static void sleep (long millis) throws InterruptedException
Parameters: millis => the duration of time in milliseconds for which the thread sleeps.
Return Value: void

Throws:

  • IllegalArgumentException => if millis is negative
  • InterruptedException => if any other thread interrupts the current thread. When this exception occurs, the interrupted status of the thread is cleared.

Description: This variation of sleep method makes the current thread to sleep or temporarily stops its execution for the given number of milliseconds (provided in method argument). However, while sleeping, the thread does not lose the monitor or lock ownership.

#2) Sleep Method Variant # 2

Prototype: public static void sleep (long millis, int nanos) throws InterruptdException
Parameters:

  • millis => the duration in milliseconds for which the thread has to sleep.
  • nanos => additional nanoseconds for which the thread can sleep. The range is 0 – 999999.

Return value: void
Throws:

  • IllegalArgumentException => if millis value is negative or nanos value if out of range.
  • InterruptedException => if any other thread interrupts the current thread. The interrupted status of the thread is cleared when this exception occurs.

Description: This variant of the sleep method causes the thread to invoke it to sleep or temporarily stop its execution for the given number of milliseconds. (first argument in a method call). Besides, it also provided the number of nanoseconds (second argument in a method call) for sleeping.

Note that the accuracy and precision of the time specified depends on the system timers and schedulers. When the thread is sleeping, the ownership of the lock or monitor is not changed.

Working Of Thread.Sleep Method

Whenever a thread sleeps or is suspended, it is done by the scheduler. The method Thread.sleep() communicates with the thread scheduler so that the scheduler can cause the currently running thread to change to wait for the state for a given duration.

Once this specified time is over, the state of the thread is changed to ‘runnable’ so that it can wait for the CPU to proceed with the execution.

Thus the duration for how long the thread sleeps does depend on the scheduler and not the method. As the scheduler is a part of the Operating system, the OS architecture also plays a role in the state changes of the thread.

Now that we have seen the Thread.sleep() method in detail, we should keep some of the points in mind while using this method.

Pointers Include:

#1) Thread.sleep() method always pauses the execution of the current thread.

#2) The actual duration for which the thread sleeps depends on the schedulers and system timers.

For example, for a very busy system, the sleeping time of the thread may be longer than the specified whereas, for the system that is not so busy, it might be more or less near to a specified time.

#3) While the thread is sleeping, it doesn’t lose any locks or monitors that it had acquired before sleeping.

#4) The current thread that is in sleep can be interrupted by any other thread. In this case, “InterruptedException” is thrown.

Thread.sleep Example In Java

Let's now move on to an example that demonstrates the sleep method. Here, we have a thread class that has a run () method. In the run () method we call ‘Thread.sleep (1000)’. Then in the main function, we create two instances of this thread i.e. two threads. We then start the threads.

In the output, we notice that as both the threads are running, the threads are scheduled one after the other i.e. when one sleeps the other is running.

Example:

class SleepThread extends Thread  {    
    //run method for thread
    public void run()    {    
        for(int i=1;i<5;i++)   {    
            try  {  
                //call sleep method of thread
                Thread.sleep(1000);  
            }catch(InterruptedException e){System.out.println(e);}    
            //print current thread instance with loop variable
            System.out.println(Thread.currentThread().getName() + "   : " + i);    
        }    
    }    
}
class Main{
    public static void main(String args[])  
    {  
        //create two thread instances
        SleepThread thread_1 = new SleepThread();    
        SleepThread thread_2 = new SleepThread();    
        //start threads one by one
        thread_1.start();    
        thread_2.start();    
    }    
}  

Output:

Thread.sleep example in Java - Output

When we observe the output, we find that Thread_0 and Thread_1 take turns to execute.

Thread.sleep() With Negative Sleep Time Value

Next, let's demonstrate another example of the Thread.sleep() method. Here we have considered a special case of a negative sleep time value. The program is similar to the above program but the sleep time provided is -500.

Example:

class SleepThread extends Thread  {    
    public void run()    {    
        for(int i=1;i<5;i++)    {    
            try     {  
                //call sleep method with negative value of time
                Thread.sleep(-500);   
            }catch(InterruptedException e){System.out.println(e);}    
            System.out.println(i);    
        }    
    } 
}
class Main{
    public static void main(String args[])   {    
        //create two thread instances
        SleepThread t1=new SleepThread();    
        SleepThread t2=new SleepThread();    
        //start the threads one by one
        t1.start();    
        t2.start();    
    }    
}  

Output:

Thread.sleep () with negative sleep time value - output

From the output, we can see that the method has thrown ‘IllegalArgumentException’ as the negative value of sleep time is not acceptable.

Frequently Asked Questions

Q #1) How does thread sleep work in Java?

Answer: When the sleep() is called on the thread with a specified amount of time in milliseconds, the thread ceases its execution. It relinquishes the CPU.  Thus, during the duration when the thread is asleep, the other threads can use the CPU.

Q #2) What is yield() and sleep() in thread Java?

Answer: The sleep() method of thread causes the thread to relinquish the CPU and cease the execution. While this thread sleeps, the other threads acquire CPU. This is done by the scheduler.

The yield() method also causes the thread to give up the CPU control when called but the sleep() method exhibits more determined behavior when compared to yield().

Q #3) How do you stop a Java thread from going to sleep?

Answer: We stop Java thread from sleeping using the interrupt() method. Any thread that is waiting or sleeping can be interrupted by invoking the interrupt() method of the Thread class.

Q #4) Can we kill a thread in Java?

Answer: No, the thread is not killed in Java. Instead, the thread is stopped in Java. The thread is terminated and then can shut down gracefully. We often use a volatile boolean field that is periodically checked for any changes in values, so that we can terminate the thread.

Q #5) Why is sleep() a static method?

Answer: When calling sleep() method to put the thread to sleep, we always call it using the Thread class.

For example, Thread.sleep (1000);

The above call works in the current thread context and puts the current thread to sleep. We never call the method using a specific thread instance. Thus the method is static.

Conclusion

In this tutorial, we have discussed the sleep() method of threads in Java. Sleep() method causes the current thread that is executing to cease its execution for a specified amount of time that is provided as an argument to the sleep method.

The system scheduler works with the sleep method to put the current thread in the waiting state. While the thread is sleeping, it continues to possess the locks or monitors that it has acquired. When we pass a negative value of sleep time to the sleep method, it throws ‘IllegalArgumentException’.

When we pass a valid sleep time value to the sleep () method, the other threads will take the turn to execute while the current thread sleeps.

=> Check Here To See A-Z Of Java Training Tutorials Here.