参考文档
https://blog.csdn.net/blog_empire/article/details/86693851
1.demo
package com.br.doublelive.redis;
import javafx.concurrent.Worker;
public class InterruptExceptionTest {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Worker());
t.start();
Thread.sleep(100);
t.interrupt();
System.out.println("Main thread stopped.");
}
public static class Worker implements Runnable {
@Override
public void run() {
System.out.println("Worker started.");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("抛出异常JVM会清除线程的中断状态 Worker IsInterrupted--------: " +
Thread.currentThread().isInterrupted());
// TODO: 2019/1/29 对抛出的InterruptedException的正确处理应该是设置Thread.currentThread().interrupt();
Thread.currentThread().interrupt();
System.out.println("执行interrupt()设置线程的中断状态 Worker IsInterrupted--------: " +
Thread.currentThread().isInterrupted());
/**
* 清除线程的中断状态
*/
Thread.interrupted();
System.out.println("清除线程的中断状态interrupted(); Worker IsInterrupted--------: " +
Thread.currentThread().isInterrupted());
}
System.out.println("Worker stopped.");
}
}
}
2.以上代码执行结果
Worker started.
抛出异常JVM会清除线程的中断状态 Worker IsInterrupted--------: false
执行interrupt()设置线程的中断状态 Worker IsInterrupted--------: true
清除线程的中断状态interrupted(); Worker IsInterrupted--------: false
Worker stopped.
Main thread stopped.
3.如果把Thread.interrupted();注释掉
Worker started.
Main thread stopped.
抛出异常JVM会清除线程的中断状态 Worker IsInterrupted--------: false
执行interrupt()设置线程的中断状态 Worker IsInterrupted--------: true
清除线程的中断状态interrupted(); Worker IsInterrupted--------: true
Worker stopped.
4.如果把Thread.currentThread().interrupt()注释掉
Worker started.
Main thread stopped.
抛出异常JVM会清除线程的中断状态 Worker IsInterrupted--------: false
执行interrupt()设置线程的中断状态 Worker IsInterrupted--------: false
清除线程的中断状态interrupted(); Worker IsInterrupted--------: false
Worker stopped.