gpt4 book ai didi

java - 处理 InterruptedException 的最佳方法

转载 作者:行者123 更新时间:2023-11-30 08:40:19 25 4
gpt4 key购买 nike

我正在使用 Thread.sleep(10000);因此我需要处理 InterruptedException。我可以调用 Thread.currentThread.interrupt() 然后将异常抛给调用类或者我可以直接将它抛给调用类还是有更好的方法来处理它?<​​/p>

最佳答案

如果你有一个循环和轮询的专用线程,对我来说这听起来像是程序结束时需要终止的东西;除非它是一个守护线程(暗示你很高兴它消失而没有机会清理或关闭资源)它需要能够处理中断。使用 WatchService 似乎是个好主意,但使用 WatchService 的代码仍然必须知道如何处理中断。

如果你正在编写一个 hibernate 的 Runnable 或 Callable,你可以使用 InterruptedException 来退出你正在做的任何循环,或者你可以捕获异常并恢复中断标志,以便下一次检查中断标志(使用Thread.currentThread().isInterrupted())可以看出线程已经中断了:

while(!Thread.currentThread().isInterrupted()){  
//do something
try{
Thread.sleep(5000);
} catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}

或者,您可以使用 InterruptedException 来跳出循环:

try {
while (!Thread.currentThread().isInterrupted()) {
// do something
Thread.sleep(5000);
}
} catch (InterruptedException e) {
// flag value is not used here
Thread.currentThread().interrupt();
}

如果您正在开发一个您希望嵌套在其他对象中的对象,则抛出异常并将其添加到方法签名中。作为示例,请查看 java.util.concurrent 包中类的 API 文档,例如 BlockingQueue ,查看 put 和 offer 等方法如何抛出 InterruptedException。当为并发而创建的对象组合在一起时,它们需要合作(并确保它们不会丢失对中断状态的跟踪),以确保它们能够以响应方式清理和终止。

关于java - 处理 InterruptedException 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35723085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com