1 isInterrupted
- 作用 : 判断线程状态是否为中断
- 调用方式 :new Thread().isInterrupted()
- 注意:如果 isInterrupted方法返回的是true,那么就一定是调用了 intertupt ()方法
2 intertupt
- 作用 : 修改线程状态为 “中断”
- 调用方式 :new Thread().interrupt();
3 interrupted
- 作用 : 返回线程目前的中断状态,同时清空状态(即设置状态为 false)
- 调用方式 :Thread.interrupted()
-
方法内部代码 public static boolean interrupted() { return currentThread().isInterrupted(true); }
/**
* 1 isInterrupted 用来判断线程的中断状态,如果被中断则 为 ture
* 2 interrupt() 中断的方法,如果线程处于 无事可做的情况下(例如 sleep 的时候)则可以直接中断线程,否则只改变线程的中断状态
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
a1();
a2();
}
/**
* 一个线程不管在启动前,还是启动后他的 中断状态都是 false
* 下面的方法是在线程启动前后分别执行 isInterrupted() 方法,然后得到结果都是false
*
* @throws InterruptedException
*/
public static void a1() throws InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("执行完毕");
});
System.out.println(thread.isInterrupted());
thread.start();
Thread.sleep(2000);
System.out.println(thread.isInterrupted());
}
/**
* interrupted()的主要作用是返回现有的中断状态,然后再清除中断状态(即 设置中断状态为 false)
*
* @throws InterruptedException
*/
public static void a2() throws InterruptedException {
Thread.currentThread().interrupt();
System.out.println(Thread.interrupted());
System.out.println(Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread().isInterrupted());
}
}