How to Properly Stop a Java Thread: Methods, Examples, and Pitfalls
This article explains the various ways to terminate a running Java thread—including using exit flags, the deprecated stop() method, interrupt(), and exception handling—illustrates each approach with code samples, compares Thread.interrupted() and isInterrupted(), and discusses the dangers of forceful termination and lock release.
Stopping a thread means abandoning its current operation before the task completes. While Thread.stop() can halt a running thread, it is unsafe and deprecated, so it should be avoided.
In Java there are three common ways to terminate a running thread:
Use an exit flag so the thread finishes its run() method and exits normally.
Call the stop() method, which forces termination but is discouraged because it is obsolete.
Invoke interrupt() to set an interrupt flag that the thread can check.
1. Threads That Cannot Be Stopped
The interrupt() method does not immediately break a loop; it merely sets an interrupt flag on the current thread.
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 is set on the main thread, not on the worker thread.
2. Determining a Thread’s Interrupt State
Two methods are provided by Thread :
Thread.interrupted() – tests and clears the interrupt status of the current thread.
Thread.isInterrupted() – tests the interrupt status without clearing it.
Example code demonstrates the difference: the first call returns false after the flag is cleared, while isInterrupted() returns true twice.
3. Stopping a Thread with an Exception
By checking this.interrupted() inside a loop and throwing InterruptedException , the loop can be exited cleanly:
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));
}
} catch (InterruptedException e) {
System.out.println("Caught in MyThread.run()");
e.printStackTrace();
}
}
}The catch block handles cleanup after the interrupt.
4. Stopping a Sleeping Thread
If a thread is in sleep() and receives an interrupt, it throws InterruptedException and the interrupt status is cleared:
public class MyThread extends Thread {
public void run() {
super.run();
try {
System.out.println("Thread starts…");
Thread.sleep(200000);
System.out.println("Thread ends.");
} catch (InterruptedException e) {
System.out.println("Interrupted while sleeping, isInterrupted(): " + this.isInterrupted());
e.printStackTrace();
}
}
}The output shows the flag becomes false after the exception.
5. Forceful Stop with stop()
Using stop() terminates a thread abruptly, which can leave shared resources in an inconsistent state. Example code demonstrates a thread printing numbers until stop() is called.
6. stop() and java.lang.ThreadDeath
Calling stop() throws a ThreadDeath error, which is usually not caught explicitly. The error can bypass finally blocks and leave locks unreleased.
7. Bad Consequences of Releasing Locks via stop()
When stop() releases a synchronized lock, the protected data may become inconsistent. The article shows a class with synchronized setters that can be left half‑updated when the thread is stopped.
8. Stopping a Thread by Returning
Combining interrupt() 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());
}
}
}The main method sleeps briefly, interrupts the thread, and the worker thread exits after printing a final message.
Overall, the article recommends using interrupt‑driven termination with proper exception handling rather than the deprecated stop() method.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.