如何在Java中使用超时调用一些阻塞方法?

编程入门 行业动态 更新时间:2024-10-13 16:18:37
本文介绍了如何在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中使用超时调用一些阻塞方法?

本文发布于:2023-08-04 09:13:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1295014.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   如何在   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!