deepfuture 发表于 2013-2-3 10:45:41

java-通过Future来取消任务

向ExecutorService提交了任务,并通过定时的Future.get获得结果。如果get终止于一个TimeoutExeception,那么任务是由Future取消的,如果深层计算在取消前就抛出一个异常,在timedRun中会重新被抛出。
Future有一个cancel方法,它需要一个boolean类型的参数,mayInterruptIfRunning,它的返回值表示取消尝试是否成功。当mayInterruptIfRunning为true,并且任务当前正在运行一些线程中,那么这个线程是应中断的。把这个参数设为false意味着如何还没启动,就不要运行这个事务了。
public static void timedRun(Runnable r,long timeout,TimeUnitunit)
throws InterruptedException{
  Future<?>task=taskExec.submit(r);
   try{
       task.get(timeout,unit);
   }
   catch (TimeoutExceptione){
     //下面任务会被取消
   }
   catch (ExecutionExceptione){
     //task中抛出的异常;重抛出
     throw launderThrowable(e.getCause());
   }
   finally{
     //如果任务已经结束,是无害的
     task.cancerl(true);
   }
}
页: [1]
查看完整版本: java-通过Future来取消任务