Stopping a Thread: Use boolean value to stop a thread : Thread Stop « Thread « Java Tutorial






class CounterThread extends Thread {
  public boolean stopped = false;

  int count = 0;

  public void run() {
    while (!stopped) {
      try {
        sleep(1000);
      } catch (InterruptedException e) {
      }
      System.out.println(count++);
      ;
    }
  }
}

public class MainClass {

  public static void main(String[] args) {
    CounterThread thread = new CounterThread();
    thread.start();
    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
    }
    thread.stopped = true;
    System.out.println("exit");
  }

}
0
1
2
3
4
5
6
7
8
9
exit








10.4.Thread Stop
10.4.1.Stopping a Thread: Use boolean value to stop a thread
10.4.2.Stopping a Thread with interrupt()
10.4.3.Suspend, resume, and stop a thread.
10.4.4.To determine whether a thread has been interrupted