我正在阅读Interrupts来自 Oracle 文档。我无法弄清楚以下内容 部分。它指出
What if a thread goes a long time without invoking a method that throws InterruptedException? Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received. For example:
for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}
我绞尽脑汁想明白,如果线程过长怎么办? 时间而不调用抛出 InterruptedException 的方法?其次,有什么用途 Thread.interrupted(),它是一种方法,线程可以向自己发送中断?什么是 这个场景的实际用途?谢谢。
最佳答案
这是一种保持线程可被中断的技术。
Thread.interrupted() :
检查当前线程(本身)是否被其他线程中断并清除中断状态标志。因此,它会问自己,当我正在执行一项巨大的任务并且没有听别人说话时,是否被某人打断退出正在做的事情。
想象一下如果不做那件事会发生什么。
假设 heavyCrunch()
的一次迭代需要 1 分钟的时间。因此 n 次迭代将花费 n 分钟。
现在假设启动程序后您决定退出程序并正常终止程序。因此,您中断了正在执行繁重任务的线程。 但线程不知道您已中断它,因为它没有检查中断状态。因此,直到N 分钟未完成时,程序才会结束,您将不得不等待很长时间。
因此,为了优雅地终止线程,它应该始终检查中断状态,以便在其他人请求中断时做出响应。
关于java - 理解 Thread.interrupt() 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18100130/