如何停止一个正在运行的线程?

答案

正确停止线程的姿势是:

思路A

public static void main(String[] args) throws InterruptedException {
  Thread t1 = new Thread(() -> {
    try {
      Random r = new Random();
      for (int i = 0;; i++) {
        // Thread.sleep(r.nextInt(100));
        if (Thread.currentThread().isInterrupted()) {
          System.out.println("ready to stop...");
          return;
        }
        System.out.println(i + " " + Thread.currentThread().isInterrupted());
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("ready to stop cause exception...");
    } finally {
      System.out.println("stop...");
    }
  });
  t1.start();
  Thread.sleep(200);
  t1.interrupt();
  t1.join();
}

要点

使用 t1.interrupt() 配合 t1.isInterrupted()来进行停止执行

思路B

private static volatile boolean isStop = false;

public static void main(String[] args) throws InterruptedException {
  Thread t1 = new Thread(() -> {
    try {
      Random r = new Random();
      for (int i = 0;; i++) {
        // Thread.sleep(r.nextInt(100));
        if (isStop) {
          System.out.println("ready to stop...");
          return;
        }
        System.out.println(i + " " + Thread.currentThread().isInterrupted());
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("ready to stop cause exception...");
    } finally {
      System.out.println("stop...");
    }
  });
  t1.start();
  Thread.sleep(200);
  isStop = true;
  t1.join();
}

要点

使用 volatile 的布尔变量作为判断是否停止的标志位

错误思路

  • 使用线程对象的 stop() 方法停止线程
  • 使用 System.exit(int) 方法停止线程

results matching ""

    No results matching ""