我想實現迭代加深(增量樹構建)。這是我的代碼的一部分,我會問:JAVA:如何在特定時間後停止函數的執行?
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<Integer>> callables = new HashSet<Callable<Integer>>();
callables.add(new Callable<Integer>() {
public Integer call() throws Exception {
iterativeDeepening(depthLimit, board);
return -1;
}
});
callables.add(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(500);
return 1;
}
});
try{
executorService.invokeAny(callables, 1000, TimeUnit.MILLISECONDS);
}catch(TimeoutException | InterruptedException ex){
executorService.shutdown();
}
executorService.shutdown();
從我有時間閱讀invokeAny()限制它應該結束,因爲一旦達到限期執行的可調用對象。它在我長時間睡眠而不是我的函數iterativeDeepening(depthLimit,board)時起作用。如何使它與我的功能一起工作? 下面我的代碼粘貼到該函數:
public void iterativeDeepening(byte depthLimit, byte[] board){
for(byte depth=1;depth<depthLimit;depth++){
GameTree gameTree= new GameTree();
byte[] tempBoard = new byte[14];
for(byte i=0;i<14;i++){
tempBoard[i] = board[i];
}
Node <byte[]> root= new Node<byte[]>(tempBoard, player);
try {
gameTree.buildGameTree(depth, root);
} catch (OutOfMemoryError E) {
gameTree.eraseGameTree(depth,root);
System.gc();
}
MiniMax minimax = new MiniMax(player);
move= minimax.selectMove(depth, root);
}
}
如果你知道一個更好的辦法,使之或不知道如何成功地阻止我的函數的執行,請讓我知道。我也嘗試了一下本主題中提到的Runnable接口: How to stop execution after a certain time in Java? 但它的工作原理是一樣的。
如果你希望它是自包含的,你可以在進入循環之前存儲一個System.currentTimeMillis()變量。然後在循環的每次迭代中檢查if(System.currentTimeMillis() - startTime> = maxRunTime)。 – Radiodef
這不是一個解決方案,因爲在循環內部有一個函數gameTree.buildGameTree(深度,根);其本身有時需要比截止日期更重要的時間。 – user2923339
您可以將開始時間作爲參數傳遞。 @AndreyChaschev可能是正確的,你最好的選擇就是檢查中斷。中斷一個線程不一定會過早結束它,而無需自己檢查中斷。 – Radiodef