Home >Java >javaTutorial >How to Safely and Gracefully Stop a Java Thread?
When working with multithreading in Java, it may arise that you need to terminate a thread prematurely. To guarantee proper execution and prevent system instability, it's crucial to halt threads "gracefully." This involves allowing the thread to complete any critical operations before ending its execution.
Problem:
You have created a thread that is taking an excessive amount of time to execute. Despite appearing to be unfinished, you wish to gracefully stop the thread.
Solution:
The preferred approach to achieving this is by leveraging a boolean variable within the target thread's run() method. Setting this flag to true from the outside will signal the thread to gracefully terminate. Here's an example:
class MyThread extends Thread { volatile boolean finished = false; public void stopMe() { finished = true; } @Override public void run() { while (!finished) { // Perform tasks } } }
Avoid the stop() Method:
In the past, a Thread.stop() method existed, but its use is strongly discouraged. As per the Java documentation, this method "unlocks all of the monitors that it has locked" upon execution, leading to potential data inconsistency and arbitrary behavior.
Therefore, utilizing a boolean flag as illustrated above ensures a safe and controlled thread termination mechanism.
The above is the detailed content of How to Safely and Gracefully Stop a Java Thread?. For more information, please follow other related articles on the PHP Chinese website!