How to Stop a Thread in Java with Examples

One of the interview question on java concurrency is how to stop a thread in java. Most of the candidates answer this question by saying Thread.stop() method. But interviewer hit back by saying that Thread.stop() method is deprecated due to thread safety issues. You can find the reason why here. Interviewer continues, can you write the code on how to stop a thread in java. Here is the answer, I will be sharing two ways on how to stop a thread in java :

1.  Using boolean volatile variable
2.  Using interrupt() method

Read Also :  Java Concurrency Interview Questions

Why and when to use volatile variable instead of normal variable ?

A situation may occur when more than one threads are accessing the same variable. The changes made by one thread is not visible to other threads. To avoid such kind of situation, volatile variable is used.
A volatile variable is directly stored in the main memory. Threads can not have locally cached values of volatile variable. In other words, changes made by one thread is visible to other threads. Hence, using volatile variable makes our code thread-safe.

1. Using boolean volatile variable

In this method we have set one boolean volatile variable named exit. Initially, we set exit variable value to false. The task to be performed is kept inside the run() method's while loop. We have passed exit variable in the while loop condition. As long as exit variable remains false, the thread keeps on running.
We need to set exit variable to true in order to stop the thread. We will use stopThread() method to set the exit variable value to true. Whenever you want to stop the running thread, just call the stopThread() method.


class StopThread extends Thread {
    /* Setting the volatile variable 
       exit to false */
    private volatile boolean exit = false; 
 
    /* Call this method to set the 
       exit value to true and stop 
       the thread */
    public void stopThread() {
        exit = true;
    }
    
    @Override
    public void run(){
        // Keep the task in while loop    
        while(!exit) {
            System.out.println("Thread is running....");
        }
        System.out.println("Thread Stopped.... ");
    }
}

public class MainClass {
    public static void main(String args[]) {
 
        StopThread thread = new StopThread();
 
        // Starting thread
        thread.start();
 
        try {
            Thread.sleep(10);
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }
 
        /* run below method whenever 
        you want to stop the thread */ 
        thread.stopThread();
    }
}

Output :
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread Stopped....
 

You may be wondering why multiple times Thread is running....  are printed. It is because there are two threads in the program one is main thread and another is StopThread . In MainClass we have used Thread.sleep(10) method, which suspended the main thread for 10 milliseconds. Now, StopThread gets chance for execution. As value of exit variable is false, StopThread will keep executing the run() method while loop. Hence, print Thread is running.... .

Once main thread comes out of the suspended state, it will call stopThread() method and update the volatile variable exit value to true. Hence, StopThread will come out of the while loop. This is the reason it prints Thread Stopped.... .

How to stop a thread in java

2. Using Thread.interrupt() method

According to Oracle docs, an interrupt is signal to a thread that it should stop what it is doing. It's up to the programmer to choose how a thread responds to an interrupt. Terminating thread is very common task performed by the programmers using interrupt() method.

How Thread.interrupt() method works :

By using the boolean internal flag interrupt status ,  the interrupt mechanism is implemented. Whenever interrupt() method is called , it sets the value of flag interrupt status true. The default value of this flag is false. The status of the thread can be obtained by invoking static interrupted() method. This status can be used in the while loop to stop the thread as shown below in the code.


class StopThread extends Thread {
 
    @Override
    public void run(){
        // Keep the task in while loop    
        while(!Thread.interrupted()) {
            System.out.println("Thread is running....");
        }
        System.out.println("Thread Stopped.... ");
    }
}

public class MainClass {
    public static void main(String args[]) { 
 
        StopThread thread = new StopThread(); 
 
        // Starting thread
        thread.start(); 
 
        try {
            Thread.sleep(10);
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }
 
        /* run below method whenever 
        you want to stop the thread */ 
        thread.interrupt();
    }
}

Output :
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread is running....
Thread Stopped....


POINTS TO REMEMBER :

1. You can not use synchronize keyword with variable, if you try to do so then it will result in java compilation error. Instead of using the synchronized variable,  you can make the variable volatile. It will instruct the JVM threads to read the value of volatile variable from main memory and don't cache it locally.

2. It is a good practice to write a separate method for stopping the thread. Although, method only changes the value of boolean variable.

That's all for the post how to stop a thread in java. Please mention in the comments if you have any questions regarding the topic. I will be happy to help.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry