Completablefuture用法总结

前言

Future接口有一定的局限性,比如,我们很难表述Future结果之间的依赖性,因此在Java8中引入了CompletableFuture,它针对Future做了改进,可以传入回调对象,当异步任务完成或者发生异常时,自动调用回调对象的回调方法。

CompletableFuture对象的创建

Java8中提供了4个静态方法用来创建CompletableFuture对象,具体介绍分别如下:

通过静态方法创建CompletableFuture对象

  1. 创建一个异步线程,参数为Runnable,它的返回值为Void,内部使用的是默认的ForkJoinPool.commonPool()线程池
public static CompletableFuture<Void> runAsync(Runnable runnable) {
        return asyncRunStage(asyncPool, runnable);
}
  1. 先比于1,CompletableFuture也提供了通过指定线程池的方式来创建它的对象,如下:
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor) {
        return asyncRunStage(screenExecutor(executor), runnable);
}
  1. 上面1,2通过runAsync方式创建的CompletableFuture对象都是没有返回值的,如果需要有返回值的,需要用到它的supplyAsync方法,如下:
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return asyncSupplyStage(asyncPool, supplier);
}
  1. 同样,也可以通过指定线程池的方式传参,如下:
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor) {
        return asyncSupplyStage(screenExecutor(executor), supplier);
}

示例

	//无返回值
    private static void testRunAsync() throws Exception {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            log.info("testRunAsync begin run...");
            doSomething();
            log.info("testRunAsync run end...");
        });

        Void aVoid = future.get();
    }

    //有返回值
    private static void testSupplyAsync() throws Exception {
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
            log.info("testSupplyAsync begin run...");
            doSomething();
            log.info("testSupplyAsync run end...");
            return System.currentTimeMillis();
        });

        long time = future.get();
        log.info("future get:" + time);
    }

    private static void doSomething() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            log.info("exception:{}", e.getMessage());
        }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值