The thread is ane of of import Class inward Java in addition to multithreading is well-nigh widely used a feature,but at that spot is no clear means to halt Thread inward Java. Earlier at that spot was a halt method exists inward Thread Class only Java deprecated that method citing around security reason. By default, a Thread stops when execution of run() method complete either commonly or due to whatsoever Exception.In this article, nosotros volition How to Stop Thread inward Java past times using a boolean State variable or flag. Using a flag to halt Thread is a rattling pop way of stopping the thread in addition to it's likewise security because it doesn't produce anything particular rather than helping run() method to complete itself.
How to Stop Thread inward Java
As I said before Thread inward Java volition halt ane time run() method finished. Another of import hollo for is that y'all tin non restart a Thread which run() method has finished already , y'all volition larn an IllegalStateExceptio, hither is a Sample Code for Stopping Thread inward Java.
Sample Code to Stop Thread inward Java
someone cast Runner extends Thread{
boolean bExit = false;
world void exit(boolean bExit){
this.bExit = bExit;
}
@Override
world void run(){
while(!bExit){
System.out.println("Thread is running");
endeavour {
Thread.sleep(500);
} grab (InterruptedException ex) {
Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Should nosotros brand bExit Volatile
Since every Thread has its ain local retention inward Java its skilful exercise to brand bExit volatile because nosotros may modify the value of bExit from whatsoever thread in addition to function inward volatile guarantees that Runner volition likewise run into whatsoever update done before making bExit.
That’s all on how to halt the thread inward Java , permit me know if y'all break whatsoever other means of stopping threads inward Java without using deprecated stop() method.
Further Learning
Multithreading in addition to Parallel Computing inward Java
Java Concurrency inward Practice - The Book
How to break in addition to Avoid Deadlock inward Java