Stop threads through cooperation

In general, you should use modern libraries such as java.util.concurrent when dealing with threads. If you're forced to use a low-level Thread object, for some reason, then stopping those threads should be done with care. Threads should not be stopped using stop or suspend. These methods are deprecated.

Instead, threads should use the following simple idiom to stop in a well-behaved manner.


public final class SimpleThread implements Runnable {

  @Override public void run() {
    boolean isDone = false;
    while (!isStopRequested() && !isDone){
      //perform the work
      //if finished, set isDone to true
    }
  }

  /** Request that this thread stop running.  */
  public synchronized void requestStop(){
    fIsStopRequested = true;
  }

  // PRIVATE

  private boolean fIsStopRequested;

  private synchronized boolean isStopRequested() {
    return fIsStopRequested;
  }
} 



See Also :
Prefer modern libraries for concurrency
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -