关于在阻塞状态下中断线程的问题
来源:5-4 遇到阻塞

96年的nash
2019-08-23
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异常呢?
写回答
1回答
-
亲,由于你立刻interrupt,所以while(num <= 300 && !Thread.currentThread().isInterrupted())检测到了已经被中断,所以跳过了while语句内的执行,但是sleep是在while外面的,所以还是会执行sleep的,并且刚开始sleep就发现线程已经被中断,所以抛出异常。
112019-08-23
相似问题