Java——CompletableFuture接口解析

CompletableFuture接口说明

CompletableFuture是Future的子类,接口Future接口虽然实现了异步调用,但是存在一个问题,为了判断线程是否已完成计算,或者要获取计算结果,我们需要不断的轮询,通过循环调用Future的isDone方法或者是直接调用get的方法阻塞线程。

在JDK8中,提供了CompletableFuture类来解决这类问题,它可以在线程完成计算后用when、then等方式调用我们定义后续处理方法,省去了轮询的操作(笔者最近在读RocketMQ源码,发现在Broker上使用了CompletableFuture类,因此打算记录一下基本功能和用法,希望后续有时间能详细研读一下实现源码。)

CompletableFuture有以下几种构造方式:

//没有计算过程,直接返回计算结果
CompletableFuture<String>futureNoComplete=CompletableFuture.completedFuture("hello world");

//没有返回值的异步计算
CompletableFuture<Void>futureNoReturnNoExecutor=CompletableFuture.runAsync(()->doSomething());
CompletableFuture<Void>futureNoReturnWithExecutor=CompletableFuture.runAsync(()->doSomething(), Executors.newSingleThreadExecutor());

//带返回值的异步计算
CompletableFuture<String> futureWithReturnNoExector=CompletableFuture.supplyAsync(()->doSomethingReturnString());
CompletableFuture<String> futureWithReturnWithExecutor=CompletableFuture.supplyAsync(()->doSomethingReturnString(), Executors.newSingleThreadExecutor());

当completeFuture代表的任务完成了,可以使用一系列的函数接口来定义当前Future完成后的后续计算。

//执行完当前任务后,以当前任务的返回值作为fn任务的输入,并返回计算结果
 	public <U> CompletableFuture<U> thenApply(
        Function<? super T,? extends U> fn) {
   
        return uniApplyStage(null, fn);
    }
//执行完当前任务后,将返回值作为输入,计算fn任务,并返回结果
 	public <U> CompletableFuture<U> thenApplyAsync(
        Function<? super T,? extends U> fn) {
   
        return uniApplyStage(asyncPool, fn);
    }

//执行完当前任务后,以当前任务返回值作为输入,并返回计算结果,该计算过程使用executor中的不同线程来执行
 	public <U> CompletableFuture<U> thenApplyAsync(
        Function<? super T,? extends U> fn, Executor executor) {
   
        return uniApplyStage(screenExecutor(executor), fn);
    }

//执行完当前任务后,将返回值作为action任务的输入参数进行计算
    public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
   
        return uniAcceptStage(null, action);
    }

//执行完当前任务后,将返回值作为action任务的输入参数进行计算
    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
   
        return uniAcceptStage(asyncPool, action);
    }
//执行完当前任务后,将返回值作为action任务的输入参数进行计算
    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
                                                   Executor executor) {
   
        return uniAcceptStage(screenExecutor(executor), action);
    }
//执行完当前任务后ÿ
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值