本节我们将通过Java中的Future实现对于提交的任务进行取消。ExecutorService.submit将返回一个Future来描述任务,Future拥有一个cancel方法,该方法带有一个boolean类型的参数mayInterruptIfRunning,表示取消操作是否成功(这个参数只是表示任务是否能够接收中断,而不是表示任务是否能检测并处理中断)。如果mayInterruptIfRunning为true并且任务当前正在某个线程中运行,那么这个线程能被中断;如果这个参数是false,那么意味着“若任务还没有启动,就不要运行它”,这种方式应该用于那些不处理中断的任务中。
package test;
import java.util.concurrent.*;
/**
* @Auther: fishing
* @Date: 2018/10/14 18:05
* @Description:
*/
public class CancelFutureTask {
private ExecutorService taskExec = Executors.newCachedThreadPool();
public void timedRun(Runnable r, long timeout, TimeUnit unit) throws InterruptedException{
Future<?> task = taskExec.submit(r);
try {
task.get(timeout,unit);// 定时获取,超时之后将取消任务
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
// 如果任务已经结束,那么执行取消操作也不会带来任何影响
// 如果让任务正在执行,那么将被中断
task.cancel(true);
}
}
}