注:
方法名以”Async“结尾的区别:(如thenApply和thenApplyAsync)
thenApply:当前任务的线程继续执行“thenApply”的任务。
thenApplyAsync:把“thenApplyAsync”这个任务继续交给线程池来进行执行。
一、获得结果和触发计算
1、获取结果
get():同Future的get()。
get(long timeout, TimeUnit unit):同Future的get()。
join():同get()。join不报异常,get会报异常。
getNow(T valueIfAbsent):立即获取计算值,如果未计算完,则返回设定的默认值valueIfAbsent。
2、主动触发计算
complete(T value):立即打断异步执行。如果打断成功返回true,此时get会得到设定的默认值value。打断失败返回false,此时get会得到异步执行的结果。
二、对计算结果进行处理
...thenApply(i -> { return i + 2; }).handle((i, e) -> { return i + 3; })...
i:上一步的计算结果
e:异常
1、thenApply
计算结果存在依赖关系,step by step。
由于存在依赖关系,当前步骤异常时,不会继续下一步。
2、handle
有异常也可以继续下一步,根据带的异常参数可以进一步处理。
三、对计算结果进行消费
thenAccept:接收任务的返回结果,并消费处理,无返回结果。
四、对计算速度进行选用
applyToEither:返回最快执行完的结果。最快返回后,其他线程依然会继续执行。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static void main(String[] args) { try { CompletableFuture future = CompletableFuture.supplyAsync(() -> { try { System.out.println(Thread.currentThread().getName() + "暂停6秒钟"); TimeUnit.SECONDS.sleep(6); System.out.println(Thread.currentThread().getName() + "完成6秒钟"); } catch (InterruptedException e) { e.printStackTrace(); } return 6; }).applyToEither(CompletableFuture.supplyAsync(() -> { try { System.out.println(Thread.currentThread().getName() + "暂停5秒钟"); TimeUnit.SECONDS.sleep(5); System.out.println(Thread.currentThread().getName() + "完成5秒钟"); } catch (InterruptedException e) { e.printStackTrace(); } return 5; }), r -> r).applyToEither(CompletableFuture.supplyAsync(() -> { try { System.out.println(Thread.currentThread().getName() + "暂停4秒钟"); TimeUnit.SECONDS.sleep(4); System.out.println(Thread.currentThread().getName() + "完成4秒钟"); } catch (InterruptedException e) { e.printStackTrace(); } return 4; }), r -> r); System.out.println(future.join()); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } catch (Exception e) { } }
五、对计算结果进行合并
thenCombine:合并多个任务的执行结果。(如调用多个接口合并处理后返回前端)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static void main(String[] args) { try { CompletableFuture future = CompletableFuture.supplyAsync(() -> { return 10; }).thenCombine(CompletableFuture.supplyAsync(() -> { return 20; }), (r1, r2) -> { return r1 + r2; }); System.out.println(future.join()); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } catch (Exception e) { } }