When encountering a long-running thread that must be stopped mid-execution, it's crucial to do so gracefully to avoid unpredictable consequences.
To achieve this, a common approach is to introduce a control variable within the thread's run() method. This variable, typically a boolean flag, acts as a sentinel to signal the termination request.
Consider the following example:
class MyThread extends Thread { volatile boolean finished = false; public void stopMe() { finished = true; } @Override public void run() { while (!finished) { // Perform the necessary actions } } }
From the main thread, you can gracefully halt the execution by calling the stopMe() method:
MyThread myThread = new MyThread(); myThread.start(); // Wait some time to simulate work Thread.sleep(500); myThread.stopMe();
Previously, Java had a stop() method, but it was declared unsafe due to its potential to corrupt the thread's state and unlock acquired locks. Therefore, using the control variable approach is the recommended way to ensure a clean and controlled thread termination.
The above is the detailed content of How to Gracefully Terminate a Java Thread?. For more information, please follow other related articles on the PHP Chinese website!