isInterrupted()
Thread 方法 :返回会boolean 值,为Thread的中断状态
底层是通过调用本地方法实现 。
isInterrupted()仅会返回中断状态,不会清除中断标
interrupt()
无返回值, 会调用nio的方法,以及本地方法中断线程,
线程中断的后并不会马上停止,而是会继续执行完
interrupt()只是将中断标识位置为true
注意:线程中断仅仅是设置线程的中断状态位,不会停止线程。需要用户自己去监视线程的状态为并做处理。这里可以看到中断后该线程还在继续往下执行,并没有强制终止线程
interrupted()
返回:boolean类型, 会清空中断标记
如果线程是中断状态返回,则会返回true,并清空中断标记
第二次调用则返回false;
代码:
package com.ljq.mydemo.thread.Interrup;
/**
* @author gino
* 2021-11-30
*/
public class Interrupt {
public static void main(String[] args) {
Thread t = new Thread(new Worker());
t.start();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
System.out.println("Main thread stopped.");
}
public static class Worker implements Runnable {
@Override
public void run() {
System.out.println("Worker started.");
boolean f; // 用于检测interrupted()第一次返回值
int i = 0;
Thread c = Thread.currentThread();
System.out.println("while之前线程中断状态isInterrupted():" + c.isInterrupted());
while (!(f = Thread.interrupted())) {// 判断是否中断,如果中断,那么跳出并清除中断标志位
// 一旦检测到中断,interrupted()第一次返回true,就可以跳出循环,第二次以及以后都是返回false
System.out.println("while内,还没中断,interrupted()返回值为:" + f);
System.out.println(c.getName() + " " + i++ + " " + c.isInterrupted());
}
System.out.println("跳出循环即第一次中断interrupted()返回值:" + f);
System.out.println("while之后线程中断状态isInterrupted():" + c.isInterrupted()); // 为false,因为interrupt()会清除中断标志位,显示为未中断
System.out.println("第二次及以后的interrupted()返回值:" + Thread.interrupted());
c.interrupt();
System.out.println("再次中断后查询中断状态isInterrupted():" + c.isInterrupted());
System.out.println("Worker stopped.");
}
}
}