【发布时间】:2016-02-22 21:10:22
【问题描述】:
我想使用迭代深化来执行搜索,这意味着每次我这样做时,我都会更深入并且需要更长的时间。获得最佳结果有时间限制(2 秒)。根据我的研究,最好的方法是使用 ExecutorService、Future 并在时间用完时中断它。这是我目前拥有的:
在我的主要功能中:
ExecutorService service = Executors.newSingleThreadExecutor();
ab = new AB();
Future<Integer> f = service.submit(ab);
Integer x = 0;
try {
x = f.get(1990, TimeUnit.MILLISECONDS);
}
catch(TimeoutException e) {
System.out.println("cancelling future");
f.cancel(true);
}
catch(Exception e) {
throw new RuntimeException(e);
}
finally {
service.shutdown();
}
System.out.println(x);
还有可调用对象:
public class AB implements Callable<Integer> {
public AB() {}
public Integer call() throws Exception {
Integer x = 0;
int i = 0;
while (!Thread.interrupted()) {
x = doLongComputation(i);
i++;
}
return x;
}
}
我有两个问题:
- doLongComputation() 没有被中断,程序仅在完成工作后检查 Thread.interrupted() 是否为真。我是否需要在 doLongComputation() 中检查线程是否已被中断?
- 即使我摆脱了 doLongComputation(),主要方法也不会接收 x 的值。如何确保我的程序等待 Callable “清理”并返回迄今为止最好的 x?
【问题讨论】:
标签: java multithreading concurrency executorservice callable