如何在Java中使用超时调用一些阻塞方法? [英] How do I call some blocking method with a timeout in Java?

查看:350
本文介绍了如何在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

感谢。

推荐答案

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.

请参阅 StackDoc JavaDoc 了解更多详情。

See StackDoc and JavaDoc for more detail.

这篇关于如何在Java中使用超时调用一些阻塞方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆