How to stop a thread?
In multithreading, we start a thread using start () method and we execute thread using run() method .Similarly we also have wait(),notify and sleep() method to let thread wait or sleep for sometime. But it is difficult to stop a thread as stop() method has been deprecated. So,we need to apply some logic to stop the thread . There can be many ways to stop a thread but in this tutorial we will use Boolean flag variable to stop a thread.
Why stop() method is deprecated in java:
When we stop a thread using Thread.stop() method it causes the thread to release all the acquired monitors and throw ThreadDeath error and cauese. If any of the objects previously locked by these monitors were in an inconsistent state, then it becomes visible to other threads, which may lead the program to some unexpected behavior.
Program to stop a thread
class ThreadDemo extends Thread
private volatile boolean stopFlag = true;
public void stopThread()
stopFlag = false;
public void run()
System.out.println(Thread.currentThread().getName()+" is running");
System.out.println(Thread.currentThread().getName()+" has stopped running");
public class ThreadStopDemo
public static void main(String args)
ThreadDemo threadDemo = new ThreadDemo();
catch (InterruptedException e)
In above example, we declare one boolean volatile variable stopFlag in a thread. Set this flag value as true. Inside run() method use while loop by passing stopFlag .If flag value is true then keep the task performed in while loop and thread will continue to run until flag becomes false. We have defined stopThread() method which is called from main method after thread start .This method will set the stopFlag as false and stops the thread. Also note that we have declared flag as volatile. Every Thread has its own local memory so it is good practice to make stopFlag as volatile because value of stopFlag can be alter from any thread if not declared volatile and making it volatile guarantees that thread will always read updated value of stopFlag.