Also Read: Oracle Java Tutorials
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
private class Runner extends Thread{
boolean bExit = false;
public void exit(boolean bExit){
this.bExit = bExit;
}
@Override
public void run(){
while(!bExit){
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
How to Stop Thread in Java Tutorial ExampleSince every Thread has its own local memory in Java its good practice to make bExit volatile because we may alter the value of bExit from any thread and make it volatile guarantees that Runner will also see any update done before making bExit.
That’s all on how to stop the thread in Java , let me know if you find any other way of stopping threads in Java without using deprecated stop() method.
0 comments:
Post a Comment