Thread is one of important Class in Java and multi-threading is most widely used feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default a Thread stops when execution of run() method finish either normally or due to any Exception.In this article we will How to Stop Thread in Java by using a boolean State variable or flag. Using flag to stop Thread is very popular way of stopping thread and its also safe, because it doesn't do anything special rather than helping run() method to finish it self.
How to Stop Thread in Java
As I said earlier Thread in Java will stop once run() method finished. Another important point is that you can not restart a Thread which run() method has finished already , you will get an IllegalStateExceptio, here is a Sample Code for Stopping Thread in Java:
Sample Code to Stop Thread in Java
public class Runner extends Thread{
boolean bStopMe= false;
public void exit(){
this.bStopMe= true;
}
// or
// or
public void tellMeToStop() {
bStopMe= true;
}
@Override
public void run(){
while(!bStopMe){
System.out.println("Thread is running");
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
Should we make bExit Volatile
Since every Thread has its own local memory in Java its good practice to make bStopMevolatile because we may alter value of bStopMefrom any thread and making it volatile guarantees that Runner will also see any update done before making bExit.
That’s all on how to stop thread in Java , let me know if you find any other way of stopping threads in Java without using deprecated stop() method.
Q: I have been wondering why isn't there a method to kill a waiting, sleeping or a non running thread. Is there anyway we can do that?
A: The reason you can't just stop a thread is actually fairly simple. What if it's allocated resources, and is in the middle of work? If you do a hard stop, that may just leave a lot of stuff hanging. So, instead you basically send it a message and it stops at it's own convenience (if implemented properly). Basically they pushed back that part of the behavior to the programmers.
A: The reason you can't just stop a thread is actually fairly simple. What if it's allocated resources, and is in the middle of work? If you do a hard stop, that may just leave a lot of stuff hanging. So, instead you basically send it a message and it stops at it's own convenience (if implemented properly). Basically they pushed back that part of the behavior to the programmers.

No comments:
Post a Comment