How to pause Thread in Java using Sleep() and TimeUnit Example

There are multiple ways to pause or stop the execution of currently running thread, but putting the thread into sleep state using Thread.sleep() method is the right way to introduce pause. Some people would say, why not use wait and notify?. Using those methods just for pausing thread is not good. Those are the tools for a conditional wait and they don't depend on upon 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 wait() method is different, they are designed for inter-thread communication in Java. By using 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, a they need lock. You can only call them from a synchronized method or 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 difference between 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 require a good knowledge of Java API. You need to use the right method at the right place. If you are serious about mastering multi-threading and concurrency, I would suggest to read Java Concurrency in Practice twice and do every example given on that book. That book will change how you look a problem from multi-threading perspective.

How to pause Thread using Sleep in Java

Here is our sample Java program to pause a running thread using Thread.sleep() and TimeUnit.sleep() method in Java. In this simple program, we have two thread, 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 it 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 at closely, we have used a volatile modifier to stop a thread in Java.

Main thread first starts the thread and then stops it by using 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 main thread can wait for some time and in the meantime, T1 will resume and finished. If you have not read already then you must read Java Concurrency in Practice to gain a comprehensive understanding of multithreading in Java.

In one example, we have learned two ways to pause a thread in Java, by using Thread.sleep() method and 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 e.g. TimeUnit.SECONDS or TimeUnit.MICROSECOND before calling sleep on it. You can see its 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 why to prefer TimeUnit in Java.

Thread.sleep() and TimeUnit Example

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");
        //Now, let's stop our Game thread
        System.out.println(currentThread().getName() + " is stopping game thread");
        //Let's wait to see game thread stopped 
        System.out.println(currentThread().getName() + " is finished now");

class Game implements Runnable{
    private volatile boolean isStopped = false;
    public void run() {
            System.out.println("Game thread is running.....");            
            System.out.println("Game thread is now going to pause");
            try {
            } catch (InterruptedException e) {               
            System.out.println("Game thread is now resumed ..");
        System.out.println("Game thread is stopped....");
    public void stop(){
        isStopped = true;

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 Thread.sleep() method in Java.

How to pause a running thread in Java

1) 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 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 upon system timers and it's possible for a thread to woke before.

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

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

Further Learning
Multithreading and Parallel Computing in Java
Applying Concurrency and Multi-threading to Common Java Patterns
Java Concurrency in Practice - The Book
Java Concurrency in Practice Bundle by Heinz Kabutz

If you like this tutorial and interested in learning more about multi-threading in Java. You can also take a look at following Java multi-threading tutorials :
  • 10 things every Java programmer should know about Thread class (article)
  • What is the difference between Thread and Runnable in Java? (answer)
  • What is the difference between Process and Thread in Java? (answer)
  • Understanding the difference between wait() and sleep() in Thread? (answer)
  • What is the difference between Callable and Runnable in Java? (answer)
  • What is the difference between wait() and yield() method in Java? (answer)
  • When to use notify() and notifyAll() in Java? (answer)
  • What is the difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • The difference between yield() and sleep() method in Java? (answer)

Thanks for reading this article, if you like this tutorial then please share with your friends and colleagues.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.