Home >Java >javaTutorial >How to Gracefully Halt a Thread in Java?

How to Gracefully Halt a Thread in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 04:33:03991browse

How to Gracefully Halt a Thread in Java?

Gracefully Halting a Thread in Java

When a thread takes an excessive amount of time to execute, it may be necessary to halt it gracefully to prevent system instability. The preferred approach to achieving this is by implementing a boolean flag within the thread's run() method, as follows:

class MyThread extends Thread {
  volatile boolean finished = false;

  public void stopMe() {
    finished = true;
  }

  public void run() {
    while (!finished) {
      // Perform necessary tasks
    }
  }
}

This allows you to stop the thread from an external source by setting finished to true.

It's important to note that the outdated Thread.stop() method is inherently unsafe. As the Java documentation states, it can lead to arbitrary behavior due to the unlocking of monitors and potential inconsistencies in object states. Therefore, implementing a guard within the thread's run() method, as demonstrated above, is the recommended and safe approach to graceful thread termination.

The above is the detailed content of How to Gracefully Halt a Thread in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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