我想使用迭代深化來執行搜索,這意味着每次執行搜索時,我都會更深入,這需要更長的時間。有一個時間限制(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?
謝謝!對於第2部分,我的問題是'f.cancel(true)'不僅中斷了線程,而且完全取消了它。所以AB永遠不會到達'return x'。 – acornellier
@ user3389645:我明白你的意思了。取消可能不是你想要的。 –