Home > Java > javaTutorial > How to Gracefully Terminate a Java Thread?

How to Gracefully Terminate a Java Thread?

Linda Hamilton
Release: 2024-11-11 20:22:03
Original
835 people have browsed it

How to Gracefully Terminate a Java Thread?

How to Gracefully Terminate a Java Thread

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
    }
  }
}
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template