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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
class ThreadDemo extends Thread { private volatile boolean stopFlag = true; public void stopThread() { stopFlag = false; } @Override public void run() { while (stopFlag) { 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(); threadDemo.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } threadDemo.stopThread(); } } |
OutPut:
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.