java - 搜索方法返回的超时时间,否则会抛出超时消息

标签 java multithreading timer timeout

我想通过java main执行一个搜索方法并想实现 搜索方法返回的超时时间,否则将抛出超时消息。 如何使用线程或计时器类实现超时功能?

最佳答案

一种方法是将搜索任务提交给执行者,并且 call get(timeout); on the returned future -本质上:

  • 根据您的任务创建一个 Callable
  • 超时运行
  • 如果超时,请取消它 - 为了使取消生效,您的 Callable 需要对中断使用react
Callable<SearchResult> task = ...;
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<SearchResult> f = executor.submit(task);

SearchResult result = null;
try {
    result = f.get(2, TimeUnit.SECONDS); //2 seconds timeout
    return result;
} catch (TimeOutException e) {
    //handle the timeout, for example:
    System.out.println("The task took too long");
} finally {
    executor.shutdownNow(); //interrupts the task if it is still running
}

关于java - 搜索方法返回的超时时间,否则会抛出超时消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12766865/

相关文章:

c# - 如何在时间上递增?

java - 如何保持 fragment 中的滚动位置?

JavaFX 文本在高 DPI 上无法正确缩放

android - 是否存在线程安全计时器?

c++ - 如何提高C++中的多线程性能

c# - 如何在没有任何副作用的情况下使用 Reactive Extensions (C#) 控制计时器?

java - 衡量用户在 Java 中执行某项操作的时间的最佳方法是什么?

java - JPA:按集合值属性排序查询结果?

java - 未应用 ActiveMQ 5.7.0 redeliveryPolicy

multithreading - 并行加速和效率