JUC并发编程(1)—CompletableFuture详解
@
最近在学习juc并发编程,于是决定汇总一下并发编程中常用方法,常见问题以及常见考题,今天是第一章—CompletableFuture
CompletableFuture介绍
CompletableFuture是jdk8版本开始出现的类。目的是为了应用于并发编程状态下遇到的各种场景。CompletableFuture实现了CompletionStage接口和Future接口,对Java7及以前Future接口做了大量的扩展,增加了许多常用方法,增加了异步会点、流式处理、多个Future组合处理的能力,使Java在处理多任务的协同工作时更加顺畅便利。
首先得学会看懂几个函数式接口的特性!!!(重点)

1.创建异步任务
//runAsync方法不支持返回值
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
//supplyAsync可以支持返回值
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
CompletableFuture创建异步任务主要分为两个方法runAsync和supplyAsync
其中
- runAsync方法不支持返回值
- supplyAsync可以支持返回值(常用)
- 没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。
下面是四种创建方式
public class CompletableFutureTest {
public static void main(String[] args) throws Exception{
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5,5,5
TimeUnit.MINUTES,
new LinkedBlockingQueue<>(10));
CompletableFuture future1=CompletableFuture.runAsync(()->{
System.out.println(Thread.currentThread().getName()+"*********future1 coming in");
});
//这里获取到的值是null,无返回值
System.out.println(future1.get());
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
//ForkJoinPool.commonPool-worker-9
System.out.println(Thread.currentThread().getName() + "\t" + "*********future2 coming in");
}, executor);
CompletableFuture<Integer> future3 =CompletableFuture.supplyAsync(()-> {
//pool-1-thread-1
System.out.println(Thread.currentThread().getName() + "\t" + "future3带有返回值");
return "abc";
});
System.out.println(future3.get());
CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "\t" + "future4带有返回值");
return "abc";
}, executor);
System.out.println(future4.get());
//关闭线程池
executor.shutdown();
}
}
2.CompletableFuture API
①. 获得结果和触发计算(get、getNow、join、complete)
获得结果和触发计算(get、getNow、join、complete)
- public T get( ):不见不散(会抛出异常) 只要调用了get( )方法,不管是否计算完成都会导致阻塞
- public T get(long timeout, TimeUnit unit):过时不候
- public T getNow(T valuelfAbsent):没有计算完成的情况下,给我一个替代结果计算完,返回计算完成后的结果、没算完,返回设定的valuelfAbsent
- public T join( ):join方法和get( )方法作用一样,唯一区别是join方法编译时不需要手动抛异常

- public CompletableFuture thenApply:计算结果存在依赖关系,这两个线程串行化,由于存在依赖关系(当前步错,不走下一步),当前步骤有异常的话就叫停
- public CompletableFuture handle(BiFunction<? super T, Throwable, ? extends U> fn):有异常也可以往下一步走,根据带的异常参数可以进一步处理
- whenComplete:是执行当前任务的线程执行继续执行whenComplete的任务
- whenCompleteAsync:是执行把whenCompleteAsync这个任务继续提交给线程池来进行执行
②. 对计算结果进行处理(thenApply、handle)
- public CompletableFuture thenApply:计算结果存在依赖关系,这两个线程串行化由于存在依赖关系(当前步错,不走下一步),当前步骤有异常的话就叫停
- public CompletableFuture handle(BiFunction<? super T, Throwable, ? extends U> fn):有异常也可以往下一步走,根据带的异常参数可以进一步处理
- whenComplete:是执行当前任务的线程执行继续执行whenComplete的任务
- whenCompleteAsync:是执行把whenCompleteAsync这个任务继续提交给线程池来进行执行

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {e.printStackTrace();}
return 1;
}).thenApply(s->{
System.out.println("-----1");
//如果加上int error=1/0; 由于存在依赖关系(当前步错,不走下一步),当前步骤有异常的话就叫停
//int error=1/0;
return s+1;
}).thenApply(s->{
System.out.println("-----2");
return s+2;
}).whenComplete((v,e)->{
if(e==null){
System.out.println("result-----"+v);
}
}).exceptionally(e->{
e.printStackTrace();
return null;
});
System.out.println(Thread.currentThread().getName()+"\t"+"over....");
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {e.printStackTrace();}
CompletableFuture.supplyAsync(() -> {
return 1;
}).handle((f,e) -> {
System.out.println("-----1");
return f + 2;
}).handle((f,e) -> {
System.out.println("-----2");
int error=1/0;
return f + 3;
}).handle((f,e) -> {
System.out.println("-----3");
return f + 4;
}).whenComplete((v, e) -> {
if (e == null) {
System.out.println("----result: " + v);
}
}).exceptionally(e -> {
e.printStackTrace();
return null;
}).join());
③. 对计算结果进行消费(thenRun、thenAccept、thenApply)
- thenRun(Runnable runnable)
任务A执行完执行B,并且B不需要A的结果 - CompletableFutur thenAccept(Consumer<? super T> action)
任务A执行完成执行B,B需要A的结果,但是任务B无返回值 - public CompletableFuture thenApply(Function<? super T,? extends U> fn)

4. 线程串行化方法
带了Async的方法表示的是:会重新在线程池中启动一个线程来执行任务
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor)
public CompletableFuture<Void> thenRun(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action,Executor executor)
④. 对计算速度进行选用(applyToEither、acceptEither、runAfterEither)
- public CompletableFuture applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn)
这个方法表示的是,谁完成任务完成的快就返回谁的结果

- 两任务组合,一个完成
applyToEither:两个任务有一个执行完成,获取它的返回值,处理任务并有新的返回值
acceptEither:两个任务有一个执行完成,获取它的返回值,处理任务,没有新的返回值
runAfterEither:两个任务有一个执行完成,不需要获取 future 的结果,处理任务,也没有返回值
⑤. 对计算结果进行合并(thenCombine、thenAcceptBoth、runAfterBoth)
- public <U,V> CompletableFuture
thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn)
两个CompletionStage任务都完成后,最终把两个任务的结果一起交给thenCombine来处理先完成的先等着,等待其他分支任务

⑥. 多任务组合(allOf、anyOf)
- allOf:等待所有任务完成
(public static CompletableFutureallOf(CompletableFuture<?>... cfs)) - anyOf:只要有一个任务完成
(public static CompletableFuture

浙公网安备 33010602011771号