gpt4 book ai didi

java - 在 java 中调用超时的阻塞方法调用

转载 作者:行者123 更新时间:2023-11-29 08:05:45 26 4
gpt4 key购买 nike

我想在 java 中调用一个由于某种原因而阻塞的方法。我想等待该方法 X 分钟,然后我想停止该方法。

我在 StackOverflow 上阅读了一个解决方案,它让我快速入门。我在这里写:-

ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
return something.blockingMethod();
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// handle the timeout
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(); // may or may not desire this
}

但现在我的问题是,我的函数可能会抛出一些异常,我必须捕获这些异常并相应地执行一些任务。因此,如果在代码中函数 blockingMethod() 抛出一些异常,我该如何在外部类中捕获它们?

最佳答案

您已在您提供的代码中设置了执行此操作的所有内容。只需更换

// handle other exceptions

用你的异常处理。
如果您需要获取特定的 Exception,您可以通过以下方式获取它:

Throwable t = e.getCause();

为了区分您的异常,您可以这样做:

if (t instanceof MyException1) {
...
} else if (t instanceof MyException2) {
...
...

关于java - 在 java 中调用超时的阻塞方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11362823/

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