如何在 Java 中调用一些带有超时的阻塞方法? [英] How do I call some blocking method with a timeout in Java?
本文介绍了如何在 Java 中调用一些带有超时的阻塞方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中是否有一种标准的好方法来调用具有超时的阻塞方法?我希望能够做到:
Is there a standard nice way to call a blocking method with a timeout in Java? I want to be able to do:
// call something.blockingMethod();
// if it hasn't come back within 2 seconds, forget it
如果有道理.
谢谢.
推荐答案
您可以使用 Executor:
You could use an 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
中的常量的单位进行配置.
If the future.get
doesn't return in 5 seconds, it throws a TimeoutException
. The timeout can be configured in seconds, minutes, milliseconds or any unit available as a constant in TimeUnit
.
请参阅 JavaDoc 了解更多细节.
See the JavaDoc for more detail.
这篇关于如何在 Java 中调用一些带有超时的阻塞方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文