java 实现timeout 的问题
代码里有一个调用其他模块的方法, 但是那个方法有时候会需要很长时间, 想实现一个timeout
创建了如下代码:
package com.timeout;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TimeOutExample {
public static void print(){
int i = 0;
while(i == 0){
}
}
public static void main(String[] args) throws Exception {
Callable reservationTask = new Callable() {
public Object call() throws InterruptedException {
String s = "";
//put JCO call here
print();
return "task has runned";
}
};
final FutureTask future = new FutureTask(reservationTask);
Thread th = new Thread() {
public void run() {
future.run();
}
};
System.out.println("Start");
long start = new Date().getTime();
th.start();
try {
String result = (String)future.get(2, TimeUnit.SECONDS);
System.out.println(result);
System.out.println("end");
} catch (TimeoutException e) {
System.out.println("time out");
future.cancel(true);
e.printStackTrace();
} finally {
long end = new Date().getTime();
System.out.println("total run time" + (end - start) + "millisecond");
}
}
}
代码中 虽然throw了 timeoutexception, 但是并没用结束print方法的执行。 问下这种情况print方法调用结束了么