JUC源码解析CompletableFuture
Posted aniao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JUC源码解析CompletableFuture相关的知识,希望对你有一定的参考价值。
简介
先说Future, 它用来描述一个异步计算的结果。isDone方法可以用来检查计算是否完成,get方法可以用来获取结果,直到完成前一直阻塞当前线程,cancel方法可以取消任务。而对于结果的获取,只能通过阻塞(get())或者轮询的方式[while(!isDone)]. 阻塞的方式违背了异步编程的理念,轮询的方式耗费无谓的CPU资源(CPU空转)。于是,CompletableFuture应运而生。
样例
后面介绍的源码都会以下面的用例为切入点,循着调用轨迹理解源码。
1 public void whenComplete() { 2 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100); 3 future.whenComplete((l, r) -> System.out.println(l)); 4 } 5 6 public void thenApply() { 7 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100); 8 future.thenApply(i -> -i); 9 } 10 11 public void thenAccept() { 12 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100); 13 future.thenAccept(System.out::println); 14 } 15 16 public void thenRun() { 17 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100); 18 future.thenRun(() -> System.out.println("Done")); 19 } 20 21 public void thenAcceptBoth() { 22 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100); 23 CompletableFuture<Integer> other = CompletableFuture.supplyAsync(() -> 200); 24 future.thenAcceptBoth(other, (x, y) -> System.out.println(x + y)); 25 } 26 27 public void acceptEither() { 28 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100); 29 CompletableFuture<Integer> other = CompletableFuture.supplyAsync(() -> 200); 30 future.acceptEither(other, System.out::println); 31 32 } 33 34 public void allOf() { 35 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100); 36 CompletableFuture<Integer> second = CompletableFuture.supplyAsync(() -> 200); 37 CompletableFuture<Integer> third = CompletableFuture.supplyAsync(() -> 300); 38 CompletableFuture.allOf(future, second, third); 39 40 } 41 42 public void anyOf() throws InterruptedException, ExecutionException { 43 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100); 44 CompletableFuture<Integer> second = CompletableFuture.supplyAsync(() -> 200); 45 CompletableFuture<Integer> third = CompletableFuture.supplyAsync(() -> 300); 46 CompletableFuture.anyOf(future, second, third); 47 }
源码分析
supplyAsync
whenComplete
thenApply
thenAccept
thenRun
thenAcceptBoth
acceptEither
allOf
anyOf
行文至此结束。
尊重他人的劳动,转载请注明出处:http://www.cnblogs.com/aniao/p/aniao_cf.html
以上是关于JUC源码解析CompletableFuture的主要内容,如果未能解决你的问题,请参考以下文章
Java——聊聊JUC中的CompletableFuture
Java——聊聊JUC中的CompletableFuture