Future取消任务

Future取消任务:

**通过Future取消那些不再需要结果的任务:
//示例:

/**
 * TimedRun
 * <p/>
 * Cancelling a task using Future
 */
public class TimedRun {

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

    public static void timedRun(Runnable r, long timeout, TimeUnit unit) throws InterruptedException {
        Future<?> task = TASK_EXEC.submit(r);
        try {
            task.get(timeout, unit);
        } catch (TimeoutException e) {
            // task will be cancelled below

        } catch (ExecutionException e) {
            // exception thrown in task; rethrow
            throw LaunderThrowable.launderThrowable(e.getCause());
        } finally {
            // 如果任务已经结束,是无害的
            task.cancel(true); // interrupt if running
        }
    }
}

//当Future.get抛出InterruptedException或者TimeoutException时,如果你知道不再需要结果时,就可以调用Future.cancle来取消任务。

猜你喜欢

转载自blog.csdn.net/A169388842/article/details/80778957