public class RightWayStopThreadWithSleep {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () -> {
int num = 0;
try {
while (num <= 300 && !Thread.currentThread().isInterrupted()) {
if (num % 100 == 0) {
System.out.println(num + "是100的倍数");
}
num++;
}
//在子线程sleep时,收到主线程的interrupt信号,从而进行中断(sleep期间被中断)
Thread.sleep(1000);
} catch (InterruptedException e) {
//捕捉到主线程中对thread线程发出interrupt信号时
e.printStackTrace();
}
};
Thread thread = new Thread(runnable);
thread.start();
//解释如上
// Thread.sleep(1);
thread.interrupt();
}
}
此时的输出结果是:
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at threadcoreknowledge.stopthreads.C5_3.RightWayStopThreadWithSleep.lambda$main$0(RightWayStopThreadWithSleep.java:21)
at java.lang.Thread.run(Thread.java:748)
我在主线程中,start后立刻发出了interrupt通知
显示的是sleep异常,但是我的sleep方法是在run方法执行完整个while循环的情况下在执行,此时终止线程的应该是!Thread.currentThread().isInterrupted()这个表达式的结果啊,为什么最后报异常还是sleep异常呢?