我想通过java main执行搜索方法并希望实现 超时搜索方法返回,否则将抛出超时消息。 如何使用线程或计时器类实现此超时功能?
答案 0 :(得分:3)
一种方法是将您的搜索任务提交给执行者,call get(timeout);
on the returned future - 实质上是:
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
}