本文介绍了如何在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中使用超时调用一些阻塞方法?
发布评论