Java通过在主循环中判断Boolean来停止线程的方法示例

时间:2022-03-03 12:48:08

本文实例讲述了Java通过在主循环中判断Boolean停止线程的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package Threads;
/**
 * Created by Frank
 */
public class StopBoolean extends 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();
  }
}

希望本文所述对大家java程序设计有所帮助。