在下面的代码中,我按照预期在100秒后捕获了TimeoutException。在这一点上,我希望代码退出主要和程序终止,但它不断打印到控制台。如何让任务在超时后停止执行?如何在TimeoutException后返回FutureTask?
private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();
private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
FutureTask<T> task = new FutureTask<T>(c);
THREAD_POOL.execute(task);
return task.get(timeout, timeUnit);
}
public static void main(String[] args) {
try {
int returnCode = timedCall(new Callable<Integer>() {
public Integer call() throws Exception {
for (int i=0; i < 1000000; i++) {
System.out.println(new java.util.Date());
Thread.sleep(1000);
}
return 0;
}
}, 100, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
!task.cancelled()应该是!isCancelled()就像djna最初写的 – Zed 2009-08-15 06:24:01
我认为使用中断要好得多。首先,你的可调用代码根本不需要知道“任务”。其次,当你在可调用代码中使用各种阻塞操作时(例如'Thread.sleep()'),这些操作不会对task.isCancelled()作出反应,但通常会对中断做出反应。所以使用'cancel(true)'并且让你的代码知道中断通常是最好的方法。 (你的代码也会更普遍,因为中断机制在Java中被广泛使用) – 2009-08-15 06:35:48
我想我的观点是“中断是一种合作机制”。 (http://www.ibm.com/developerworks/java/library/j-jtp05236.html) – 2009-08-15 06:44:17