JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

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

There are many 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, they need lock. You can only call them from a synchronized method or block and acquire and release a lock is not cheap.


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.  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.
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");
        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 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.


.