通过Future来取消任务

public static void timeRun()Runnable r,long timeout,TimeUnit unit) throws InterruptedException{
    
    
  Future<?> task = taskExec.submit(r);
  try{
    
    
    task.get(timeout,unit);
  }catch(TimeoutException e){
    
    
    //接下来任务被取消
  }catch(){
    
    
    //如果在任务中抛出了异常,那么重新抛出该异常
  }finally{
    
    
    //如果任务已经结束,执行取消
    task.cancel(true);
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/118398852