How to Stop a Thread in Java? Code Example (original) (raw)

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? Example

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);

}

}

}

}

And, if you are wondering what this code do, here is full explanation:

This code defines a Java class called Runner that extends the Thread class, making it a thread itself. This Runner class is designed to run a thread that repeatedly prints "Thread is running" to the console until a specific condition (bExit) becomes true.

Here's an explanation of the key components and methods in this code:

boolean bExit: This is an instance variable (or field) of the Runner class, which is a boolean flag used to control the thread's execution. It is initially set to false.

public void exit(boolean bExit): This is a method defined within the Runner class. It allows external code to set the bExit flag, controlling when the thread should exit. When you call this method with true as the argument, it sets bExit to true, indicating that the thread should stop running.

@Override annotation: This annotation indicates that the following method (run()) is an overridden method from the Thread class. The run() method is executed when you start the thread using the start() method.

public void run(): This is the method that contains the main logic of the thread. It runs in a loop until the bExit flag becomes true.

Inside the loop:

It prints "Thread is running" to the console.

It then sleeps the thread for 500 milliseconds (half a second) using Thread.sleep(500). This sleep simulates some work being done by the thread.

The thread will continue running this loop, periodically printing "Thread is running" and sleeping, until something outside the Runner class calls the exit(true) method, setting bExit to true. When bExit becomes true, the loop will exit, and the thread will stop running.

In practice, you would create an instance of the Runner class, start it using the start() method, and then, when you want the thread to stop, call the exit(true) method to signal the thread to exit gracefully. This is a simple way to control the lifecycle of a thread and have it perform specific tasks until you decide to stop it.

And, if you are wondering about thread lifecycle in Java, here is a nice diagram which explains how threads are created, waited, put on hold and stopped in Java:

thread lifecycle in Java

Should we make bExit Volatile?

How to Stop Thread in Java Tutorial ExampleSince every thread has its own local memory in Java it's best 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.

If you don't make it volatile, it may be possible for a thread to cache its value and keep running even if another thread has set the bExit=true, so thread will not be stopped in time.

Hence its safe to make the bExit boolean variable volatile in Java.

That’s all on how to stop the thread in Java. This one is a simple and easy way to stop a thread in Java but you should consider using Executor or ForkJoin Pool instead of creating and stopping thread manually. It's much better for Java developer to leverage thread pool to achieve concurrency and parallelism then coding your own. You can also use the parallelStream() method to run task in parallel.

Als, 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:

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

And lastly, one question for you? Why do you think Thread.stop() is deprecated? and is time to not use Thread directly and instead use Thread with Executor and ForkJoinPool?