gpt4 book ai didi

java - 在主循环内中断线程 'gracefully'

转载 作者:行者123 更新时间:2023-11-29 09:53:08 25 4
gpt4 key购买 nike

假设我有以下代码:

public void run(){
while (true){
function1();
...
functionN();
}
}

我想“优雅地”退出——这对我来说意味着一旦我发送了一个关闭信号并且当前线程在 functionK() 处,线程将“中断”循环并退出运行。

所以我试过像这样使用 Thread.interrupt():

public void run(){
while (true){
try {
function1();
...
functionN();
} catch (InterruptedException ex) {
/* Cleanup and exit. */
}
}
}

但这是行不通的 - 即使中断标志打开,线程也会继续无休止地运行。

仅作记录:

public void run(){
while (!thread.isInterrupted()){
try {
function1();
...
functionN();
} catch (InterruptedException ex) {
/* Cleanup and exit. */
}
}
}

停止循环,但对我没有帮助。由于每个函数执行的操作可能需要几分钟,并且有很多不同的函数,因此在每个函数之前检查中断标志是否是一个可能代价高昂(特别是因为大多数时候应用程序运行平稳)。

我想知道是否有一种特殊的机制可以用来解决这类问题。

最佳答案

API documentation对此非常清楚:

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an InterruptibleChannel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

因此,如果您正在等待对象监视器,则只能依赖此异常。某些 I/O 操作会抛出一些其他异常,但如果您也不使用它们,那么除了检查 interrupted() 标志外别无选择。

但您可以做的是重新组织您的代码:如果您有一个接一个调用的 N 方法,是否不可能将它们抽象成一个循环?通常可以找到重构代码以支持中断的方法,具体方法取决于您的实际场景。我的第一个问题是:为什么一个方法运行几分钟?这听起来有点可疑(尽管它可能是合理的)。

无论哪种方式,可中断性都不是免费的,如果您希望代码对中断的响应快于主循环的长度,则必须积极设计中断点。

不过还有一件事:检查 interrupted() 标志绝对不会代价高昂。当您在主循环中花费几分钟时不会,而且它比构造和处理异常要便宜得多。我什至会说,您会发现没有什么比调用 Thread.isInterrupted() 更快的了。

关于java - 在主循环内中断线程 'gracefully',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29142284/

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