1、interrupt() 线程实例方法,通知线程中断
2、Thread.interrupted() 线程静态方法,返回中断标志且清除(恢复)中断标志
3、Thread.currentThread().isInterrupted() 线程实例方法,仅返回中断标志
2 和 3 的区别:相同点:都是判断线程状态即返回线程状态
唯一区别:interrupted() 清除中断标志
isInterrupted() 不清除中断标志
public class InterruptThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +" interrupted flag is " + Thread.currentThread().isInterrupted());
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println(Thread.currentThread().getName() + " is running .");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// 响应中断,抛出异常后中断位置会被复位,自己中断自己
Thread.currentThread().interrupt();
// 注意区别在这里
System.out.println(Thread.currentThread().getName()
+" interrupted flag is " + Thread.currentThread().isInterrupted());
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new InterruptThread());
t.start();
TimeUnit.SECONDS.sleep(3);
t.interrupt();
}
}