How to pause a Thread in Java - Thread.sleep and TimeUnit.sleep Example

There are multiple ways to pause or stop the execution of the currently running thread in Java, but putting the thread into a sleep state using the Thread.sleep() method is the right way to introduce a controlled pause. Some Java programmers would say, why not use the wait and notify? Using those methods just for pausing a thread is not a good coding practice in Java. Those are the tools for a conditional wait and they don't depend on time. A thread blocked using wait() will remain to wait until the condition on which it is waiting is changed. Yes, you can put timeout there but the purpose of the wait() method is different, they are designed for inter-thread communication in Java.

By using the sleep() method, you pause the current for some given time. You should never use sleep() in place of wait() and notify() and vice-versa. There is another reason why to wait and notify should not be used to pause the thread, they need a lock. You can only call them from a synchronized method or synchronized block and acquire and release a lock is not cheap.

More importantly, why do you need to introduce lock just for pausing thread? Also one of the key differences between the wait() and sleep() method is that Thread.sleep() puts the current thread on wait but doesn't release any lock it is holding, but wait does release the lock it holds before going into blocking state. In short, multi-threading is not easy, even a simple task like creating a thread, stopping a thread, or pausing a thread requires a good knowledge of Java API. You need to use the right method at the right place.

How to pause a Thread using the Sleep method in Java?

Here is our sample Java program to pause a running thread using the Thread.sleep() and TimeUnit.sleep() method in Java. In this simple program, we have two threads, the main thread which is started by JVM and executes your Java program by invoking the public static void main(String args[]) method.


The second thread is "T1", which we have created and is used to run our game loop. The Runnable task we passed to this thread has an infinite while loop, which runs until stopped. If you look it closely, we have used a volatile modifier to stop a thread in Java. The main thread first starts the thread and then stops it by using the stop() method in our Game class which extends Runnable.

When T1 starts it goes into a game loop and then pauses for 200 milliseconds. In between, we have also put the main thread to sleep by using TimeUnit.sleep() method.

So the main thread can wait for some time and in the meantime, T1 will resume and complete its execution. If you want to learn more about Thread class and its essential methods then you can further see The Complete Java Masterclass, one of the best Java courses on Udemy to learn more about how to use the join method in Java.



Also, in just one example, we have learned two ways to pause a thread in Java, by using the Thread.sleep() method and the TimeUnit.sleep() method. The argument you pass to sleep() is time to sleep in a millisecond but that's not clear from code. This is where TimeUnit class helps. You get TimeUnit instance for a specific time unit like TimeUnit.SECONDS or TimeUnit.MICROSECOND before calling sleep on it. You can see it much more clear how long a thread will wait now. In short, use TimeUnit class' sleep() method to pause a thread because it's more readable. To learn more about TimeUnit class, see my post on why to prefer TimeUnit in Java.

Thread.sleep() and TimeUnit Example

Here is a full code example to pause a thread in Java using Thread.sleep() or TimeUnit.sleep() method in Java:

import static java.lang.Thread.currentThread;  

import java.util.concurrent.TimeUnit;  

/**  * Java Program to demonstrate how to pause a thread in Java.  
* There is no pause method, but there are multiple way to pause  
* a thread for short period of time. Two popular way is either  
* by using Thread.sleep() method or TimeUnit.sleep() method.  
*   
* @author java67  
*/

public class ThreadPauseDemo {      
    
    public static void main(String args[]) throws InterruptedException 
    {         
        Game game = new Game();  
                
        Thread t1 = new Thread(game, "T1");         
        t1.start(); 
                         
        //Now, let's stop our Game thread
        System.out.println(currentThread().getName()                       
                            + " is stopping game thread");         
        game.stop();                  
        
        //Let's wait to see game thread stopped 
        TimeUnit.MILLISECONDS.sleep(200);                  
        
        System.out.println(currentThread().getName() + " is finished now");     
      } 
}  

class Game implements Runnable{     
    private volatile boolean isStopped = false;          
    
    public void run() {                 
         while(!isStopped){             
         System.out.println("Game thread is running.....");                         
         System.out.println("Game thread is now going to pause");                          
         
         try {                 
             Thread.sleep(200);             
             } 
         catch (InterruptedException e) {                                
         e.printStackTrace();             
         }                         
        System.out.println("Game thread is now resumed ..");         
      }                  
   System.out.println("Game thread is stopped....");     
}          
    public void stop(){         
        isStopped = true;     
      } 
  }  
  
  
Output 
main is stopping game thread 
Game thread is running..... 
Game thread is now going to pause 
Game thread is now resumed .. 
Game thread is stopped.... 
main is finished now 

Important points about sleep() method :

Now you know how to put a thread on sleep or pause, it's time to know some technical details about the Thread.sleep() method in Java.

  1. The Thread.sleep() is a static method and it always puts the current thread to sleep.

  2. You can wake-up a sleeping thread by calling the interrupt() method on the thread which is sleeping.

  3. The sleep method doesn't guarantee that the thread will sleep for exactly that many milliseconds, its accuracy depends on system timers and it's possible for a thread to wake before.

  4. It doesn't release the lock it has acquired.

That's all about how to put a thread on pause by using the Thread.sleep() method and TimeUnit's sleep() method. It's better to use TimeUnit class because it improves the readability of code, but it's also not difficult to remember that argument passed to sleep() method is in a millisecond. Two key things to remember is that Thread.sleep() is a static method and always puts the current thread to sleep, and it doesn't release any lock held by the sleeping thread.



Source: Java67


The Tech Platform

www.thetechplatform.com

0 comments