How to Stop a Java Thread: Methods, Code Samples, and Common Pitfalls
This article explains various ways to terminate a running Java thread, including using exit flags, interrupt(), deprecated stop()/suspend()/resume() methods, handling InterruptedException, while providing code examples and discussing the risks of forceful termination.
This article introduces several techniques for stopping a Java thread, starting with the safest approach of using a termination flag that allows the run() method to exit naturally after completing its work.
It then describes three official ways to end a thread in Java:
Let the thread finish its run() method (normal exit).
Call interrupt() to set the interrupt flag; the thread must check the flag or catch InterruptedException to stop.
Use the deprecated stop() , suspend() and resume() methods, which are unsafe and discouraged.
Example code for the interrupt method:
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 500000; i++) {
System.out.println("i=" + (i + 1));
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
Thread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt();
}
}The article clarifies the difference between Thread.interrupted() (static, clears the flag) and Thread.isInterrupted() (instance method, does not clear the flag). It shows that calling interrupted() on the main thread after interrupting another thread returns false because the flag belongs to the current thread.
To stop a thread from within its own code, the article suggests checking isInterrupted() and returning from run() :
while (true) {
if (this.isInterrupted()) {
System.out.println("Thread stopped!");
return;
}
System.out.println("Time: " + System.currentTimeMillis());
}When a thread is blocked in Thread.sleep() , an interrupt causes an InterruptedException . The catch block clears the interrupt status, so isInterrupted() returns false after the exception.
Using the deprecated stop() method throws a java.lang.ThreadDeath error and can leave locks unreleased, leading to data inconsistency. The article demonstrates this with a synchronized object whose state becomes partially updated after a forced stop.
Finally, the article recommends avoiding stop() and instead using interruption combined with proper exception handling to terminate threads cleanly, ensuring that resources are released and program state remains consistent.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.