gpt4 book ai didi

java - 如何在 Java 中调用一些带有超时的阻塞方法?

转载 作者:IT老高 更新时间:2023-10-28 11:39:19 26 4
gpt4 key购买 nike

在 Java 中是否有标准的好方法来调用具有超时的阻塞方法?我希望能够做到:

// call something.blockingMethod();
// if it hasn't come back within 2 seconds, forget it

如果有道理的话。

谢谢。

最佳答案

你可以使用 Executor:

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(true); // may or may not desire this
}

如果 future.get 没有在 5 秒内返回,它会抛出 TimeoutException。超时可以以秒、分钟、毫秒或任何可用的单位作为 TimeUnit 中的常量进行配置。

JavaDoc了解更多详情。

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

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