我正在尝试在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;
}
答案 0 :(得分:0)
关闭ExecutorService会阻止新任务,但不会停止现有任务。您是否尝试过使用以下内容:
long t1 = System.getCurrentTimeMillis();
for (...) {
// your code
if (System.CurrentTimeMillis()-t1 > 1000*60*3) {
break; // or even return
}
}
您可以在任何地方添加类似的if
语句。它会减慢你的计算速度,但它会让它像你期望的那样停止。
答案 1 :(得分:0)
你不能立即结束递归(除非你抛出异常,但我不建议这样做)。即使期望的时间过去,执行服务也不能仅仅杀死未完成的任务。我建议计算递归内部的时间,当时间过去时只返回函数 - 它仍然需要一些时间才能打破所有递归调用。或者如果可能的话,使用堆栈而不是递归,你可以在时间限制之后立即跳出函数。