CompletableFuture详解

FutureTask执行线程时,想要获取线程的执行结果,可以通过轮询futureTask.isDone()或者调用futureTask.get()方法,但两者都会阻塞,不算真正意义上的异步。
completablefuture获取异步线程执行结果的动作也是交给另外线程中的,配合回调函数返回异步线程执行结果,不会阻塞主线程。
创建异步线程的3种方式:
1.基于completablefuture对象创建
2.基于completablefuture静态方法创建
3.基于completablefuture成员方法创建

基于completablefuture对象创建

CompletableFuture<Object> objectCompletableFuture = new CompletableFuture<>();
        
        new Thread(()->{
            log.info("completablefuture异步线程执行");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            objectCompletableFuture.complete(Thread.currentThread().getName());
            log.info("completablefuture异步线程完毕");
        }).start();
    
        
        objectCompletableFuture.thenAccept(System.out::println);
       
        log.info("main线程执行");

执行结果如下:


image.png

基于completablefuture静态方法创建

public static CompletableFuture<Void> runAsync(Runnable runnable);
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor);
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor);
public static <U> CompletableFuture<U> completedFuture(U value);

runAsync表示无返回的异步任务,supplyAsync表示有返回的异步任务,两类方法参数都可以有线程池来执行异步任务,不指定线程池的话,默认使用ForkJoinPool.commonPool()

//使用CompletableFuture静态方法创建异步线程
        CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(CompletableFutureTest::Async);
        //执行成功回调
        supplyAsync.thenAccept(System.out::println);
        //执行过程异常回调
        supplyAsync.exceptionally((e)->{
            e.printStackTrace();
            return "异步任务执行异常";
        });

基于completablefuture成员方法创建

// 可以基于CompletableFuture对象接着创建一个有返回任务
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 <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, 
                                    ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, 
                                    ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, 
                                    ? extends U> fn,Executor executor);

// 可以基于CompletableFuture对象接着创建一个无返回任务
CompletionStage<Void> thenRun(Runnable action); 
CompletionStage<Void> thenRunAsync(Runnable action); 
CompletionStage<Void> thenRunAsync(Runnable action,Executor executor); 

// 与thenApply方法类似,但是thenApply方法操作的是同一个CompletableFuture
// 而该类方法则是生产新的CompletableFuture<返回值>对象进行操作
public <U> CompletableFuture<U> thenCompose(Function<? super T, 
                        ? extends CompletionStage<U>> fn);
public <U> CompletableFuture<U> thenComposeAsync(
        Function<? super T, ? extends CompletionStage<U>> fn);
public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, 
                ? extends CompletionStage<U>> fn,Executor executor)

①thenApply类:此类方法可以基于上一个任务再创建一个新的有返回型任务。
②handle类:与thenApply类作用相同,不同点在于thenApply类方法只能在上一个任务执行正常的情况下才能执行,当上一个任务执行抛出异常后则不会执行。而handle类在上个任务出现异常的情况下也可以接着执行。
③thenRun类:此类方法可以基于上一个任务再创建一个新的无返回型任务。
④thenCompose类:与thenApply类大致相同,不同点在于每次向下传递都是新的CompletableFuture对象,而thenApply向下传递的都是同一个CompletableFuture对象对象
注意的是,这些方法有些后面为Async,区别在于如果调用方法名不带Async的方法创建出的任务都是由上一个任务的执行线程来执行的,在上一个任务没有执行完成的情况下,当前创建出来的任务会等待上一个任务执行完成后再执行。而如果是通过Async这类方法创建出来的任务则不受到这个限制,通过调用方法名带Async的方法创建出的任务,具体的执行线程会根据实际情况来决定,主要会分为如下三种情况。
①上一个任务已经执行结束了,那么当前创建出的任务会交给上个任务的执行线程来执行
②上一个任务还没有执行结束,那么则会另启一条线程来执行
③如果创建任务时指定了执行线程池,则会使用指定线程池的线程来执行
实例代码如下:

 CompletableFuture<String> supplyAsync1 = CompletableFuture.supplyAsync(CompletableFutureTest::Async);
        //链式创建 基于上个任务的返回继续执行新的任务
        supplyAsync1.thenApply(r->{
            System.out.println("获取上一个任务执行结果:"+r);
            return r+"thenapply";
        }).thenAcceptAsync(r->{
            System.out.println("获取上一个任务执行结果:"+r);
            Integer i = 1/0;
        }).handle((param,throwable)->{
            if (throwable == null){
                return param+"success";
            }
            //获取捕获异常
            System.out.println(throwable.getMessage());
            return "handle-上一个任务异常依旧可以继续执行新任务";
        }).thenCompose(x->
            CompletableFuture.supplyAsync(()->x+1)
        ).thenRun(()->{
            System.out.println("无返回任务");
        });
        //主线程休眠
        // 因为如果不为CompletableFuture指定线程池执行任务的情况下,
        // CompletableFuture默认是使用ForkJoinPool.commonPool()的线程
        // 同时是作为main线程的守护线程进行的,如果main挂了,执行异步任
        // 务的线程也会随之终止结束,并不会继续执行异步任务
        Thread.sleep(3000);
    
    
    }
    
    public static String Async(){
        
        log.info("异步线程async");
        return "ASync";
        
    }

执行结果:


image.png

异步结果获取及回调

// 阻塞主线程获取执行结果(与FutureTask.get()一致)
public T get();
// 上个方法的超时版本
public T get(long timeout,TimeUnit unit);
// 尝试获取执行结果,执行完成返回执行结果,未完成返回任务参数
public T getNow(T valueIfAbsent);
// 阻塞主线程等待任务执行结束
public T join();
// 无返回的异步任务正常执行完成后可以通过此方法写出返回值
public boolean complete(T value);
// 无返回的异步任务执行异常后可以通过此方法写出捕获的异常信息
public boolean completeExceptionally(Throwable ex);

// 任务正常执行完成后的回调函数:默认由执行任务的线程执行回调逻辑
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
// 任务正常执行完成后的回调函数:另启一条线程执行回调逻辑
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
// 任务正常执行完成后的回调函数:指定线程池执行回调逻辑
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,
                                Executor executor);
// 执行过程中出现异常时执行的回调方法
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)
                                
// 执行结束后会执行的回调逻辑
public CompletableFuture<T> whenComplete(BiConsumer<? super T,
                            ? super Throwable> action)
// 上个方法的异步版本
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,
                            ? super Throwable> action)
// 上个方法的指定线程池版本
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,
                            ? super Throwable> action, Executor executor)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容