在线程中处理取消时,经常会看到这样的代码
while (!shutdown) {
.. do something, if a blocking call, then it will throw the interrupted exception
try { .. some more ... }
catch (InterruptedException e) {
shutdown = true;
}
}
我想知道的是,是不是这样,或者为什么这样,比这样做更好
try {
while (true) {
.. do something, if a blocking call, then it will throw the interrupted exception
if (Thread.interrupted()) throw new InterruptedException();
}
} catch (InterruptedException e) {
.. clean up, let thread end
}
我的看法是,在后一种情况下,您根本不需要理会 shutdown var。
最佳答案
在第一个版本中,您可以与调用代码共享关闭标志(或类似的关闭机制),允许它仅通过设置标志就可以尝试完全正常关闭,而不会中断线程——可能回退到中断如果正常关机失败。
我不建议使用线程中断作为您唯一的关闭机制。
(同样,当然,要小心处理共享标志的方式。您需要使其成为线程安全的;在简单情况下,volatile 变量可能就足够了。)
关于Java 线程 : Shutdown flag vs Catching Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5513092/