通过 Future 来实现取消

Future 拥有一个 cancel 方法,该方法带有一个 boolean 类型的参数 mayInterruptIfRunning:

  • 如果 mayInterruptIfRunning 为 true 并且任务当前正在某个线程中运行,那么这个线程将被中断

  • 如果这个参数为 false,那么意味着“若任务还没有启动,就不要运行它”

private static ExecutorService taskExec = Executors.newCachedThreadPool();

public static void timeRun(Runnable r, long timeout, TimeUnit unit) 
        throws InterruptedException {
    Future<?> task = taskExec.submit(r);
    try {
        task.get(timeout, unit);
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    } catch (TimeoutException e) {
        e.printStackTrace();
    } finally {
        task.cancel(true);
    }
}

最后更新于