我想通过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/