栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

CompletableFuture相关用法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

CompletableFuture相关用法

由于guava中Listenablefuture的成功,在Java 8中,设计师们也新加了一个包含50个方法左右的类CompletableFuture。它的优点就是异步编程,同时这个类的使用也相当抽象…非常抽象

构造

它可以直接被new出来,此时它被当做Future来使用

CompletableFuture completableFuture = new CompletableFuture();
//传入参数,这个方法只能调用一次
completableFuture.complete(rpcResponse);
//传入异常,这个方法只能调用一次
completableFuture.completeExceptionally()
//用isDone来判断任务是否执行完毕
completableFuture.isDone();
//输出里面存的值
System.out.println(completableFuture.get());
 

但是在一般的使用中我们不会这么简单,来看看正常的构造

public static  CompletableFuture supplyAsync(Supplier supplier);
public static  CompletableFuture supplyAsync(Supplier supplier, Executor executor);

public static CompletableFuture runAsync(Runnable runnable);
public static CompletableFuture runAsync(Runnable runnable, Executor executor);

supply族的方法,可以返回异步线程执行之后的结果
run族的方法不会返回结果,像Runnable一样就只是执行线程任务

而且一般使用带线程池的方法,如果不这么做的化,该方法就会默认使用系统及公共线程池ForkJoinPool,而且这些线程都是守护线程。如果将我们普通的用户线程设置成守护线程,当我们的程序主线程结束,JVM中不存在其余用户线程,那么CompletableFuture的守护线程会直接退出,造成任务无法完成的问题

总之,不要用默认的线程池!下面是个正常的例子

        CompletableFuture completableFuture = CompletableFuture.supplyAsync(new Supplier() {
            @Override
            public Object get() {
                return null;
            }
        }, MyThreadPool.getPoolExecutor());
 

supplyAsync()方法接受的参数是Supplier,它是一个功能接口,代表结果的提供者

Supplier只有一个get()方法,可以返回通用类型的值,在这里它的返回值就是CompletableFuture里存的值,而接口所传入的参数类型就是返回值的参数类型

获取结果

以下是可以拿到CompletableFuture中存放的值的方法

public T    get()
public T    get(long timeout, TimeUnit unit)
public T    getNow(T valueIfAbsent)
public T    join()
处理结果

这是CompletableFuture的灵魂,我们可以用一些方法对得到的CompletableFuture进行进一步的处理

public CompletableFuture whenComplete(BiConsumer action)
public CompletableFuture whenCompleteAsync(BiConsumer action)
public CompletableFuture whenCompleteAsync(BiConsumer action, Executor executor)

public  CompletableFuture handle(BiFunction fn)
public  CompletableFuture handleAsync(BiFunction fn)
public  CompletableFuture handleAsync(BiFunction fn, Executor executor)

public  CompletableFuture thenApply(Function fn)
public  CompletableFuture thenApplyAsync(Function fn)
public  CompletableFuture thenApplyAsync(Function fn, Executor executor)

public CompletableFuture thenAccept(Consumer action)
public CompletableFuture thenAcceptAsync(Consumer action)
public CompletableFuture thenAcceptAsync(Consumer action, Executor executor)

public CompletableFuture exceptionally(Function fn)

找不同,来找找他们有什么相同点?

  • 四组里所有带Executor executor的方法都是传入一个自己的线程池去执行,不带的则是使用默认线程池
  • 四组里所有不带Async的方法都不使用异步处理
  • whenComplete组都会提供,一个返回结果和可抛出异常
  • handle组同样提供两个参数,一个返回结果和可抛出异常,与whenComplete组区别就是可以返回自定义参数类型的CompletableFuture
  • thenApply组只提供一个返回结果,并且可以返回自定义参数类型的CompletableFuture,同时,两个异步计算之间相互独立,互不依赖
  • thenAccept返回的CompletableFuture是空返回,不能从回调函数中获取返回结果,用这个组的方法来终结链式调用。与这个相似的是thenRun组的方法,区别是thenRun组不能访问异步计算的结果
  • exceptionally方法直接抓获所有异常

以下是一个简单的lamda表达式的例子,thenApply中Function接口只需要实现一个apply方法,接口传入的第一个参数是方法的入参类型,第二个是返回值类型

        CompletableFuture completableFuture = CompletableFuture.supplyAsync((Supplier) () -> "hello", MyThreadPool.getPoolExecutor())
                .thenApply(s -> s + "world");
        System.out.println(completableFuture.get());
 
组合 

CompletableFuture提供一些方法按顺序链接两个CompletableFuture对象

public  CompletableFuture thenCompose(Function> fn)
public  CompletableFuture thenComposeAsync(Function> fn)
public  CompletableFuture thenComposeAsync(Function> fn,Executor executor)

该方法可以按顺序链接两个CompletableFuture对象,它会将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序

thenCombine组同样可以组合两个CompletableFuture对象,它会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序

并行运行任务

CompletableFuture使用静态的allOf与anyOf来并行运行任务,中间的task1到task6都是CompletableFuture对象

CompletableFuture headerFuture = CompletableFuture.allOf(task1,.....,task6);
CompletableFuture headerFuture = CompletableFuture.anyOf(task1,.....,task6);

allOf方法等待所有任务执行完毕之后才返回,join() 可以让程序等任务都运行完了之后再继续执行
anyOf只等待第一个任务执行完毕之后就返回,如果任务错误也会返回异常

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号