原理解释:使用interrupt来通知,而不是强制(普通情况下停止线程)
while内try/catch的问题 中断被清除 sleep的设计理念,会把interrupt的标记位给清除
1.优先选择:传递中断
/**
* 最佳实践:catch了InterruptedExcetion之后的优先选择,在方法签名中抛出异常
* try catch在内 已经把异常给吞了,while这里检测不到异常 所以要把异常返回回去
*
*/
public class RightWayStopThreadInProd implements Runnable{
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new RightWayStopThreadInProd());
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
@Override
public void run() {
//run方法抛出exception
while (true && !Thread.currentThread().isInterrupted()){
System.out.println("go");
try {
throwInMethod();
} catch (InterruptedException e) {
System.out.println("保存日志");
e.printStackTrace();
}
}
}
/**
* 在休眠过程中 去中断
* 在签名中实现
* @throws InterruptedException
*/
private void throwInMethod() throws InterruptedException {
Thread.sleep(1000);
/*try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
}
2.不想或无法传递:恢复中断
如果不能抛出中断。要如何做?
如果不想或无法传递InterruptedException(例如用run方法的时候,就不让该方法Throws InterruptedException),那么应该选择在catch子句中调用Thread.currentThread().interrupt()来恢复设置中断状态,以便于在后续的执行中依然能够检查到刚才发生了中断。