How to Safely Stop a Java Thread: Methods, Pitfalls, and Best Practices
This article explains the three ways to terminate a Java thread, demonstrates how interrupt flags and isInterrupted() differ, shows how to stop threads using exceptions, sleep interruption, and the deprecated stop() method, and warns about lock‑release issues caused by forceful termination.
Introduction
Stopping a thread means ending its execution before it finishes its current task. Although Thread.stop() can halt a thread, it is unsafe and deprecated, so alternative approaches are preferred.
Ways to terminate a thread in Java
Use a termination flag and let the thread exit normally when run() completes.
Call the deprecated stop() method (not recommended).
Interrupt the thread with interrupt().
Threads that cannot be stopped with interrupt()
The interrupt() method only sets an interrupt flag; it does not immediately break a loop. The following example shows a thread that continues to run after interrupt() is called.
public class MyThread extends Thread {
public void run(){
super.run();
for(int i=0;i<500000;i++){
System.out.println("i="+(i+1));
}
}
}
public class Run {
public static void main(String args[]){
Thread thread = new MyThread();
thread.start();
try{
Thread.sleep(2000);
thread.interrupt();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}Output shows the loop runs to completion because the interrupt flag alone does not stop the loop.
Checking interrupt status
Java provides two methods: Thread.interrupted() – tests the current thread’s interrupt status and clears the flag. Thread.isInterrupted() – tests a specific thread’s interrupt status without clearing it.
public class Run {
public static void main(String args[]){
Thread thread = new MyThread();
thread.start();
try{
Thread.sleep(2000);
thread.interrupt();
System.out.println("stop 1??" + thread.interrupted());
System.out.println("stop 2??" + thread.interrupted());
}catch(InterruptedException e){
e.printStackTrace();
}
}
}Both calls to interrupted() return false because the flag is cleared after the first call; the current thread is the main thread, which was never interrupted.
Stopping a thread with an exception (break out of a loop)
By checking this.interrupted() inside a loop and throwing an InterruptedException, the thread can exit both the loop and the surrounding method.
public class MyThread extends Thread {
public void run(){
super.run();
try{
for(int i=0;i<500000;i++){
if(this.interrupted()){
System.out.println("Thread terminated, for loop stops");
throw new InterruptedException();
}
System.out.println("i="+(i+1));
}
System.out.println("This code would run after the loop");
}catch(InterruptedException e){
System.out.println("Caught in MyThread.run()");
e.printStackTrace();
}
}
}Stopping a thread while it is sleeping
If a thread is blocked in Thread.sleep(), an interrupt causes an InterruptedException to be thrown and clears the interrupt flag.
public class MyThread extends Thread {
public void run(){
try{
System.out.println("Thread starts...");
Thread.sleep(200000);
System.out.println("Thread ends.");
}catch(InterruptedException e){
System.out.println("Interrupted during sleep, isInterrupted=" + this.isInterrupted());
e.printStackTrace();
}
}
}Forceful stop() method and its problems
The deprecated stop() method throws a java.lang.ThreadDeath error, releases any held locks, and can leave shared data in an inconsistent state.
public class MyThread extends Thread {
public void run(){
while(true){
System.out.println("i="+i);
i++;
Thread.sleep(200);
}
}
}
public class Run {
public static void main(String args[]) throws InterruptedException{
Thread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.stop(); // unsafe, deprecated
}
}Using stop() can also release locks prematurely, leading to data races, as shown in a synchronized example where the password field remains unchanged after a forced stop.
Using return to stop a thread
Combining isInterrupted() with a return statement allows graceful termination.
public class MyThread extends Thread {
public void run(){
while(true){
if(this.isInterrupted()){
System.out.println("Thread stopped!");
return;
}
System.out.println("Time: "+System.currentTimeMillis());
}
}
}
public class Run {
public static void main(String args[]) throws InterruptedException{
Thread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt();
}
}Although this works, throwing an exception is often preferred because it can propagate the stop event to callers.
Original source: https://www.cnblogs.com/greta/p/5624839.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
