Monday, October 18, 2021

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 waiting 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 acquiring and releasing 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. 

If you are serious about mastering multi-threading and concurrency, I would suggest joining a fundamental course for Java threads like Multithreading and Parallel Computing in Java from Udemy. It's also very affordable and you can get in just $9.9 on Udemy sales. 



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.

How to pause a running thread 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.


Other Java Concurrency Articles You may Like
If you like this tutorial and are interested in learning more about multi-threading in Java. You can also take a look at the following Java multi-threading tutorials :
  • The Complete Java Developer RoadMap (roadmap)
  • 5 Courses to Learn Java Multithreading in-depth (courses)
  • When to use notify() and notifyAll() in Java? (answer)
  • 10 Java Multithreading and Concurrency Best Practices (article)
  • How to avoid deadlock in Java? (answer)
  • Understanding the flow of data and code in Java program (answer)
  • What is the difference between Callable and Runnable in Java? (answer)
  • How to do inter-thread communication in Java using wait-notify? (answer)
  • 10 Tips to become a better Java Developer (tips)
  • Difference between volatile, synchronized, and atomic (answer)
  • What is the difference between the wait() and yield() methods in Java? (answer)
  • Top 50 Multithreading and Concurrency Questions in Java (questions)
  • What is the difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • Top 5 Books to Master Concurrency in Java (books)
  • What is the difference between Thread and Runnable in Java? (answer)
  • Executor, Executors, and ExecutorService in Java (answer)
  • What is the difference between Process and Thread in Java? (answer)
  • ForkJoinPool and Executor Framework in Java(answer)
  • How to join two threads in Java? (answer)
  • What is Happens Before in Java Concurrency? (answer)
  • The difference between yield() and sleep() method in Java? (answer)

Thanks for reading this article so far. If you like this example of pausing a thread in Java and my explanation then please share it with your friends and colleagues. If you have any questions for feedback then please drop a comment. 

P. S. - If you are just started with Java and want to master Threads in Java but looking for a free online training course to start with then I also, suggest you check out this awesome free Java Multithreading course on Udemy. This course is absolutely free and thousands of java developers have already joined this course.

No comments:

Post a Comment

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