我正在尝试用java编写一个搜索(ids)程序,如果3分钟过去并且还没有找到解决方案,该程序就会停止。我尝试使用 while 循环,但是即使找到解决方案,循环仍然继续,但时间限制仍然存在,所以我将其更改为使用 Executor 服务,但这也不断重复。我认为执行者工作不正常。我做错了什么??
public void search(Node head) throws InterruptedException, ExecutionException{
solution = new Stack<Node>();
allnodes = 0;
ExecutorService es = Executors.newSingleThreadExecutor();
Future f = es.submit(new Runnable() {
@Override
public void run() {
startTime = System.nanoTime();
while(!Thread.interrupted()) {
endTime = searching(start);
}
long time = endTime - startTime;
System.out.printf("Finished task after %,d ns%n"+ time);
}
});
try {// stops if the task completes.
f.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
f.cancel(true);
}
es.shutdown();
}
public long searching(Node head){
solution.push(head);
if((head.getRow() == goal.getRow()) && (head.getCol() == goal.getCol())){
System.out.println("solution");
endTime = System.currentTimeMillis();
solution.push(head);
allnodes = allnodes+1;
return endTime; //here it returns the end time to then be printed out but the loop keeps going?
}
//recursively calling
int r = head.getRow();
int c = head.getCol();
if((r-1 >-1 )){
if(gr.getstate(r - 1, c) == State.Unvisited){
allnodes = allnodes+1;
System.out.println("go north");
gr.updatemap(r - 1, c);
solution.push(head);
searching(head.getN(head));
}
}
if(r+1 < (map[1].length-1)){
if(gr.getstate(r + 1, c) == State.Unvisited){
System.out.println("go south");
allnodes = allnodes+1;
gr.updatemap(r + 1, c);
solution.push(head);
head = head.getS(head);
searching(head);
}
}
if(c+1 < map.length-1){
if(gr.getstate(r , c +1) == State.Unvisited){
allnodes = allnodes+1;
System.out.println("go east");
gr.updatemap(r , c +1);
solution.push(head);
head = head.getE(head);
searching(head);
}
}
if(c -1 > -1){
if (gr.getstate(r, c-1) == State.Unvisited){
System.out.println("go west");
allnodes = allnodes+1;
gr.updatemap(r, c-1);
solution.push(head);
head = head.getW(head);
searching(head);
}
}
return endTime;
}
最佳答案
关闭 ExecutorService 会阻止新任务,但不会停止现有任务。您是否尝试过使用类似的东西:
long t1 = System.getCurrentTimeMillis();
for (...) {
// your code
if (System.CurrentTimeMillis()-t1 > 1000*60*3) {
break; // or even return
}
}
您可以在任意位置放置类似的 if
语句。它会减慢你的计算速度,但会导致它按照你的预期停止。
关于java - java中递归方法的时间限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636829/