How to Safely Stop a Java Thread: From interrupt() to stop() and Beyond
This article explains multiple techniques for terminating a Java thread—including using interrupt flags, checking thread state with isInterrupted(), handling InterruptedException, and why the deprecated stop() method is unsafe—providing code examples, output results, and cautions about lock release and data consistency.
1. Why Stopping a Thread Matters
Stopping a thread means ending its execution before the task finishes, effectively abandoning the current work. Although Thread.stop() can halt a running thread, it is unsafe and has been deprecated, so three safer alternatives are presented: using an exit flag, using interrupt(), and avoiding the obsolete stop() method.
2. Using interrupt() to Signal a Thread
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) {
Thread thread = new MyThread();
thread.start();
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}The interrupt call only sets a flag; the loop continues until it finishes, as shown by the output that reaches the final index.
3. Determining Whether a Thread Is Stopped
Two methods are available in Thread: 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 prints show false because interrupted() clears the flag after the first call. Using isInterrupted() would return true twice.
4. Stopping a Thread by Throwing an Exception
public class MyThread extends Thread {
public void run() {
try {
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println("Thread terminated, breaking loop");
throw new InterruptedException();
}
System.out.println("i=" + (i + 1));
}
} catch (InterruptedException e) {
System.out.println("Caught in MyThread");
e.printStackTrace();
}
}
}When the interrupt flag is detected, the loop breaks and an InterruptedException is thrown, allowing the thread to exit cleanly.
5. Interrupting a Sleeping Thread
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 while sleeping, isInterrupted=" + this.isInterrupted());
e.printStackTrace();
}
}
}Calling interrupt() while the thread is in sleep() triggers an InterruptedException and clears the interrupt status, as the printed flag is false.
6. The Dangerous stop() Method
Calling Thread.stop() abruptly terminates a thread, throwing a java.lang.ThreadDeath error. This can leave shared resources in an inconsistent state and release locks prematurely.
7. Consequences of Releasing Locks Prematurely
public class SynchronizedObject {
private String name = "a";
private String password = "aa";
public synchronized void printString(String name, String password) {
try {
this.name = name;
Thread.sleep(100000);
this.password = password;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String getName() { return name; }
public String getPassword() { return password; }
}
public class MyThread extends Thread {
private SynchronizedObject obj;
public MyThread(SynchronizedObject obj) { this.obj = obj; }
public void run() { obj.printString("b", "bb"); }
}
public class Run {
public static void main(String[] args) throws InterruptedException {
SynchronizedObject obj = new SynchronizedObject();
Thread t = new MyThread(obj);
t.start();
Thread.sleep(500);
t.stop(); // unsafe
System.out.println(obj.getName() + " " + obj.getPassword());
}
}The output shows b aa, demonstrating that the lock was released before password could be updated, leading to data inconsistency.
8. Stopping a Thread with return
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 t = new MyThread();
t.start();
Thread.sleep(2000);
t.interrupt();
}
}The thread detects the interrupt flag, prints a stop message, and exits via return. Although functional, using an exception‑based approach is generally preferred because it can propagate the stop event.
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.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
