gpt4 book ai didi

java - 在 Java 8 中使复杂方法可中断

转载 作者:行者123 更新时间:2023-11-29 03:01:13 24 4
gpt4 key购买 nike

我有非常复杂的方法,几乎​​没有循环和其他方法调用。我想让中断此方法成为可能。我发现这样做的唯一解决方案是检查是否 Thread.currentThread().isInterrupted()。问题是我想在每个循环的每次迭代和其他几个地方检查它。这样做之后,代码看起来并不那么好。

所以真的有两个问题。
1. 当线程被中断时,除了一遍又一遍地检查同一个标志,还有其他方法可以停止该方法吗?
2. 是在每个循环中添加 !Thread.currentThread().isInterrupted() 条件还是使用类似下面的方法更好 - 主要是为了提高性能?

void checkIfInterrupted() {
if (Thread.interrupted()) {
throw new InterruptedException();
}
}

最佳答案

首选方法是在线程中的每个循环中检查 Thread.currentThread().isInterrupted()。即。 Java 并发实践 - 听力 7.5:

class PrimeProducer extends Thread {

private final BlockingQueue<BigInteger> queue;

PrimeProducer(BlockingQueue<BigInteger> queue) {
this.queue = queue;
}

public void run() {
try {
BigInteger p = BigInteger.ONE;
while (!Thread.currentThread().isInterrupted())
queue.put(p = p.nextProbablePrime());
} catch (InterruptedException consumed) {
/* Allow thread to exit */
}
}

public void cancel() { interrupt(); }
}

There are two points in each loop iteration where interruption may be detected: in the blocking put call, and by explicitly polling the interrupted status in the loop header. The explicit test is not strictly necessary here because of the blocking put call, but it makes PrimeProducer more responsive to interruption because it checks for interruption before starting the lengthy task of searching for a prime, rather than after. When calls to interruptible blocking methods are not frequent enough to deliver the desired responsiveness, explicitly testing the interrupted status can help.

关于java - 在 Java 8 中使复杂方法可中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34786514/

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