Stop thread Java

The thread is one of the important Classes in Java and multithreading is the most widely used feature, but there is no clear way to stop Thread in Java. Earlier there was a stop method that exists in Thread Class but Java deprecated that method citing some safety reasons. By default, a Thread stops when the execution of run() method finishes 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 a flag to stop Thread is a very popular way of stopping the thread and it's also safe because it doesn't do anything special rather than helping run() method to finish itself.



How to Stop Thread in Java

As I said earlier Thread in Java will stop once the run() method is 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?

Stop thread Java
Since every thread has its own local memory in Java it's 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.

Thats 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 the deprecated stop() method.



Related Java Multi-threading Post:
How to detect and Avoid Deadlock in Java
How Synchronization Works in Java
How Volatile Keyword Works in Java
Top 15 multi-threading Interview Questions in Java
How to implement Thread in Java
Why Wait and Notify needs to be called from Synchronized Contex
Top Enum Examples in Java
What is an abstraction in Java?
Generics Tutorial in Java for Programmers

P. S. - And, if you are serious about mastering Java multi-threading and concurrency then I also suggest you take a look at these Java Concurrency and Multithreading Courses. It's an advanced resource to become an expert in Multithreading, concurrency, and Parallel programming in Java with a strong emphasis on high performance