线程中断

我们可以通过使用 interrupt() 方法中断一个活动的线程。

这个方法调用在线程只是一个指示。它是由线程如何响应中断。

通过静态方法 Thread.interrupted() 检测线程是否中断。也可通过线程类的实例方法 isInterrupted() 测试一个线程是否被中断。

示例: 中断主线程并打印线程中断状态的代码

public class Main {
    public static void main(String[] args) {
        System.out.println("#1:" + Thread.interrupted());
        // Now interrupt the main thread
        Thread.currentThread().interrupt();
        // Check if it has been interrupted
        System.out.println("#2:" + Thread.currentThread().isInterrupted());
        // Check if it has been interrupted
        System.out.println("#3:" + Thread.currentThread().isInterrupted());
        // Check if it has been interrupted
        System.out.println("#4:" + Thread.currentThread().isInterrupted());
        // Check if it has been interrupted
        System.out.println("#5:" + Thread.currentThread().isInterrupted());
        // Check if it has been interrupted
        System.out.println("#6:" + Thread.interrupted());
        // Check if it has been interrupted
        System.out.println("#7:" + Thread.interrupted());
        // Check if it has been interrupted
        System.out.println("#8:" + Thread.currentThread().isInterrupted());
        // Check if it has been interrupted
        System.out.println("#9:" + Thread.currentThread().isInterrupted());
        // Check if it has been interrupted
        System.out.println("#10:" + Thread.currentThread().isInterrupted());
    }
}

结果:

#1:false
#2:true
#3:true
#4:true
#5:true
#6:true
#7:false
#8:false
#9:false
#10:false

总结: 调用 Thread.interrupted() 会恢复线程为非中断状态


示例: 一个线程将中断另一个线程

以下示例, 子线程运行1ms后被父线程终止

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(Main::run);
        t.start();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
    }
    private static void run() {
        int counter = 0;
        while (!Thread.interrupted()) {
            counter++;
        }
        System.out.println("Counter:" + counter);
    }
}

结果:

Counter:68608

示例: 中断一个被阻塞的线程

如果在这三种方法上阻塞的线程被中断,则抛出一个InterruptedException,并清除线程的中断状态。

以下代码启动一个休眠一秒的线程,并打印一条消息,直到它被中断。

public class Main {
  public static void main(String[] args) throws InterruptedException{
    Thread t = new Thread(Main::run);
    t.start();
    Thread.sleep(5000);
    t.interrupt();
  }
  public static void run() {
    int counter = 1;
    while (true) {
      try {
        Thread.sleep(1000);
        System.out.println("Counter:" + counter++);
      } catch (InterruptedException e) {
        System.out.println("I got  interrupted!");
      }
    }
  }
}

结果:

Counter:1
Counter:2
Counter:3
Counter:4
I got  interrupted!
Counter:5
Counter:6
Counter:7
...

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress