@Override
public void run() {
try {
while (!Thread.interrupted()) {
while (!car.waxOn) {
car.waxOn();
}
}
} catch (InterruptedException e) {
System.out.println("waxon interrupted");
}
}
@Override
public void run() {
while (!Thread.interrupted()) {
while (!car.waxOn) {
try {
car.waxOn();
} catch (InterruptedException e) {
System.out.println("waxon interrupted");
}
}
}
}
上下两个run方法比较,while (!Thread.interrupted()) 判断应该放在try代码快里。否则像下面的写法,catch会吞掉InterruptedException,到时判断检测不出来以至于shutdownNow关不掉线程
shutdownNow的原理是为每个线程调用 interruput方法,然后有run方法里的判断语句来检查Thread.interrupted()
深入理解Java多线程中断机制及运行时异常处理
本文详细阐述了Java多线程中`Thread.interrupted()`方法的作用,强调了在循环判断中将`while(!Thread.interrupted())`置于`try`代码块内的必要性,以确保`InterruptedException`能够被正确捕获和处理,从而实现线程的优雅退出。通过实例演示了不当使用可能导致的问题,并提供了避免此类问题的方法。
812

被折叠的 条评论
为什么被折叠?



