Example of Java stopping a thread by judging Boolean in the main loop

  • 2020-06-23 00:14:08
  • OfStack

This article shows how Java can stop a thread by determining Boolean in the main loop. To share for your reference, specific as follows:


package Threads;
/**
 * Created by Frank
 */
public class StopBoolean extends Thread {
  //  Make sure changes are visible to other threads (mainly the main thread) 
  protected volatile boolean done = false;
  public void run() {
    while (!done) {
      System.out.println("StopBoolean running");
      try {
        sleep(720);
      } catch (InterruptedException e) {
        return;
      }
    }
    System.out.println("StopBoolean finished");
  }
  public void shutDown() {
    done = true;
  }
  public static void main(String[] args) throws InterruptedException {
    StopBoolean t1 = new StopBoolean();
    t1.start();
    Thread.sleep(1000 * 5);
    t1.shutDown();
  }
}

I hope this article has been helpful in java programming.


Related articles: