如何获得FutureTask在TimeoutException之后返回?

在下面的代码中,我按预期在100秒后捕获了TimeoutException。在这一点上,我希望代码从main退出,而程序终止,但它会一直打印到控制台。如何使任务在超时后停止执行?

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;

}

}

回答:

您需要在超时时取消任务(并中断其线程)。那就是cancel(true)方法。:

private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();

private static <T> T timedCall(FutureTask<T> task, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {

THREAD_POOL.execute(task);

return task.get(timeout, timeUnit);

}

public static void main(String[] args) {

try {

FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {

public Integer call() throws Exception {

for (int i=0; i < 1000000; i++) {

if (Thread.interrupted()) return 1;

System.out.println(new java.util.Date());

Thread.sleep(1000);

}

return 0;

}

});

int returnCode = timedCall(task, 100, TimeUnit.SECONDS);

} catch (Exception e) {

e.printStackTrace();

task.cancel(true);

}

return;

}

以上是 如何获得FutureTask在TimeoutException之后返回? 的全部内容, 来源链接: utcz.com/qa/402459.html

回到顶部