常见的两种创建线程的方式。一种是直接继承Thread,另外一种就是实现Runnable接口。
这两种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果。
从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。
Future模式的核心思想是能够让主线程将原来需要同步等待的这段时间用来做其他的事情。(因为可以异步获得执行结果,所以不用一直同步等待去获得执行结果)。
上图简单描述了不使用Future和使用Future的区别,不使用Future模式,主线程在invoke完一些耗时逻辑之后需要等待,这个耗时逻辑在实际应用中可能是一次RPC调用,可能是一个本地IO操作等。B图表达的是使用Future模式之后,我们主线程在invoke之后可以立即返回,去做其他的事情,回头再来看看刚才提交的invoke有没有结果。
示例代码,方便理解:
public class FutureTest { public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(2); // 创建Future Future future = executorService.submit(() -> { System.out.println("任务执行中"); Thread.sleep(2 * 1000); return new Random().nextInt(100); }); int index = 0; while (true) { System.out.println("等待结果中"); if (future.isDone()) { // 从Future获取结果 System.out.println("等到结果:" + future.get()); executorService.shutdown(); break; } // 取消Future if (index > 2) { // 传入一个boolean参数,来选择是否中断正在运行的task。 future.cancel(true); executorService.shutdown(); break; } index++; Thread.sleep(500); } System.out.println("流程结束"); } }
打印结果:
等待结果中 任务执行中 等待结果中 等待结果中 等待结果中 流程结束 Process finished with exit code 0
如果我们把取消的代码注释掉,打印结果:
等待结果中 任务执行中 等待结果中 等待结果中 等待结果中 等待结果中 等到结果:36 流程结束 Process finished with exit code 0
END
Java小强
未曾清贫难成人,不经打击老天真。
自古英雄出炼狱,从来富贵入凡尘。
发表评论: