interrupt之中断状态标记
interrupt中断机制中有如下方法:
- Thread.interrupt(),设置当前中断标记为true(类似属性的set方法)
- Thread.isInterrupted(),检测当前的中断标记(类似属性的get方法)
- Thread.interrupted(),检测当前的中断标记,然后重置中断标记为false(类似属性的get方法+set方法)
因此interrupt中断机制并不是真正的将当前线程中断,而是一个中断标记的变化
示例:
public class InterruptTest {
private static class Thread1 extends Thread {
@Override
public void run() {
long time = System.currentTimeMillis();
int num = 0;
while (true) {
num++;
//1 跳出while循环
if (isInterrupted()) {
System.out.println("当前线程 isInterrupted");
break;
}
if (num % 100 == 0) {
System.out.println(num + " 时间:" + (System.currentTimeMillis() - time));
}
// 3 调用sleep后要捕获InterruptedException作出相应处理
// 因为不处理的话 isInterrupted永远会false,导致无法跳出此while循环
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
thread1.start();
//2 延时调用interrupt中断改变interrupt状态为true
try {
Thread.sleep(3000);
thread1.interrupt();
System.out.println("执行中断");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}