【README】
本文总结于 《java并发编程实战》 page121,非常棒的一本书;
【1】Future
1,介绍:future 用于管理任务的生命周期,处理异常,以及实现取消;
2,future.cancel() 取消方法有一个boolean类型的参数 mayInterruptIfRunning, 表示取消操作是否成功;如果为ture,并任务当前正在某个线程中执行,则该线程能被中断;
【1.1】例子:
通过 future.cancel(true) 中断任务所属线程;
/**
* @Description future取消任务测试
* @author xiao tang
* @version 1.0.0
* @createTime 2022年02月20日
*/
public class FutureCancelTest {
static ExecutorService executorService = Executors.newFixedThreadPool(3);
public static void main(String[] args) throws Exception {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("【子线程】任务开始运行");
while(!Thread.currentThread().isInterrupted()) {
try {
System.out.println("【子线程】睡眠3秒");
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
System.out.println("【子线程】抛出中断异常");
Thread.currentThread().interrupt(); // 重置中断状态 tag2
}
}
System.out.println("【子线程】任务结束");
}
};
timeRun(runnable, 1, TimeUnit.SECONDS);
// 关闭线程池
executorService.shutdown();
System.out.println("【主线程】关闭线程池");
}
static void timeRun(Runnable r, long timeout, TimeUnit timeUnit) throws Exception {
Future<?> future = executorService.submit(r);
try {
System.out.println("【主线程】调用get() 阻塞");
future.get(timeout, timeUnit);
} catch (TimeoutException e1) {
System.out.println("【主线程】超时异常");
} catch (ExecutionException e2) {
System.out.println("【主线程】任务执行异常");
throw e2;
} finally {
System.out.println("【主线程】取消任务");
future.cancel(true); // 如果任务正在运行,那么将被中断 tag1
}
}
}
打印结果:
【主线程】调用get() 阻塞
【子线程】任务开始运行
【子线程】睡眠3秒
【主线程】超时异常
【主线程】取消任务
【子线程】抛出中断异常
【子线程】任务结束
【主线程】关闭线程池
【代码解说】
tag1的代码,取消任务,传入的参数为true,则会中断任务所属线程,即设置该子线程的中断状态为true;
- 情况1)如果这个时候子线程调用 中断式阻塞方法,如sleep,join等,则java底层会抛出中断异常,且清空中断状态(即设置为false); 如果 删除tag2(重置中断状态为true) 的代码,那么循环不会结束,子线程无法正常结束,所以需要tag2;
- 情况2)如果这个时候 子线程没有调用中断式阻塞方法,这个时候 while循环条件不满足(因为这个时候线程中断状态为true),所以子线程退出循环;
无论怎样,只要保证 tag2代码存在,不管是哪一种情况,总是可以使得子线程运行结束(任务运行结束);