Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added lines to reset interrupted status

...

Code Block
bgColor#FFcccc
final class ControlledStop implements Runnable {
  private boolean done = false;
 
  public void run() {
    while (!done) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public void shutdown() {
    done = true;
  }
}

...

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private volatile boolean done = false;
 
  public void run() {
    while (!done) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public void shutdown() {
    done = true;
  }
}

...

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private AtomicBoolean done = new AtomicBoolean(false);
 
  public void run() {
    while (!done.get()) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public void shutdown() {
    done.set(true);
  }
}

...

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private boolean done = false;
 
  public void run() {
    while (!isDone()) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public synchronized boolean isDone() {
    return done;
  }

  public synchronized void shutdown() {
    done = true;
  }
}

...