gpt4 book ai didi

java - 在 Callable 中处理 Thread.interrupted() 的正确方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:23:23 24 4
gpt4 key购买 nike

在 Callable 中处理 Thread.interrupted() 的正确方法是什么?我猜可调用对象应该抛出一个 InterruptedException;例如:

public class MyCallable implements Callable<Object> {
public Object call() {
Object result = null;

// Simulate long-running operation that calculates result
while (true) {
...
if (Thread.interrupted()) {
throw new InterruptedException();
}
}

result = ... // something produced by the long-running operation

return result;
}
}

这是正确的,还是有更合适的处理方式?谢谢。

最佳答案

编辑:

经过一些来回,您似乎希望能够中断您的 IO 例程。对于某些 NIO InterrutibleChannel 类来说,这似乎是一项不错的工作。例如,从下面的 BufferedReader 中读取是可中断的,并且会抛出 InterruptedIOException。在这里查看 more examples of the NIO code .

BufferedReader in = new BufferedReader(new InputStreamReader(
Channels.newInputStream((new FileInputStream(
new File(...))).getChannel())));

然后,您可以调用 future.cancel(),这将中断您的线程并导致 IO 抛出 InterruptedIOException。如果发生这种情况,您可以捕获IOException 并让它从call() 方法中流出。


如果您想将 call() 方法中断的情况传回给 Future,那么我认为抛出 InterruptedException 就可以了。另一种选择是仅 return null;call() 方法中的其他标记对象。如果线程被中断,我通常会这样做。

要记住的一件事是,如果 call() 抛出 InterruptedException,当您执行 future.get() 时,它会抛出一个ExecutionException 并且该异常的原因 将是 InterruptedException。如果 get(long timeout, TimeUnit unit) 超时,请不要混淆 future.get() 本身也会抛出 InterruptedException .

 try {
result = future.get();
} catch (ExecutionException e) {
if (e.getCause() instanceof InterruptedException) {
// call() method was interrupted
}
} catch (InterruptedException e) {
// get was interrupted
}

但是,如果 future.cancel(true) 被调用,则 future.get() 将抛出一个 CancellationException

关于java - 在 Callable 中处理 Thread.interrupted() 的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12805391/

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