0

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

4

1 回答 1

3

一种方法是将您的搜索任务提交给执行者,并调用get(timeout);返回的未来- 本质上是:

  • 使用您的任务创建一个 Callable
  • 超时运行它
  • 如果超时,请取消它 - 为了使取消生效,您的 Callable 需要对中断做出反应
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
}
于 2012-10-07T09:50:48.827 回答