我想通过java main执行一个search方法,并实现search方法返回的超时时间,否则它将抛出超时消息。如何使用线程或timer类实现此超时功能?
发布于 2012-10-07 17:50:49
一种方法是将搜索任务提交给executor和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
}https://stackoverflow.com/questions/12766865
复制相似问题