//可以很好的取消一个task,但是有一个问题,不会得到task完成的结果 //试用于不需要得到取消的任务的结果,事实上,大部分情况下,我们不要从一个取消的任务中得到结果 public class TimedRun { private static final ExecutorService taskExec = Executors.newCachedThreadPool(); public static void timedRun(Runnable r, long timeout, TimeUnit unit) throws InterruptedException { Future<?> task = taskExec.submit(r); try { task.get(timeout, unit); } catch (TimeoutException e) { // task will be cancelled below // } catch (ExecutionException e) { // exception thrown in task; rethrow // the deep exception can be found by invoker, it's importent to rethrow exception,we can't bury it. throw launderThrowable(e.getCause()); } finally { // Harmless if task already completed task.cancel(true); // interrupt if running } } } |
|
来自: moonboat > 《concurrent》