01-CompletableFuture系列-简单方法&入门示例

第一次写博客,大家多多支持,该系列是介绍CompletableFuture。

相信大家都已经使用过Future,Future的缺点很明显,那就是只能阻塞获取结果get(),或是轮询获取isDone()

CompletableFuture是Java8引入的,可以传入回调对象,当异步任务完成时,自动调用回调对象回调方法。

一、方法详解

1、创建异步执行任务的方法

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)

①返回值:runAsync无返回值、supplyAsync有返回值
②入参:runAsync接收Runnable类型的参数,supplyAsync接收Supplier类型的参数。
🌂:Runnable和Supplier都是函数式接口,可以用lambda语法
//无入参,无返回值 @FunctionalInterface public interface Runnable { public abstract void run(); }
//无入参,有返回值 @FunctionalInterface public interface Supplier<T> { T get(); }
④:Executor :可以将任务提交至默认的线程池执行,也可以在自己创建的线程池内执行。

//提供的默认线程池
private static final boolean useCommonPool =(ForkJoinPool.getCommonPoolParallelism() > 1);
private static final Executor asyncPool = useCommonPool ?ForkJoinPool.commonPool() : new ThreadPerTaskExecutor(); //new ThreadPerTaskExecutor() 开启一个新的线程

提供的默认线程池

private static final boolean useCommonPool =(ForkJoinPool.getCommonPoolParallelism() > 1);
private static final Executor asyncPool = useCommonPool ?ForkJoinPool.commonPool() : new ThreadPerTaskExecutor(); //new ThreadPerTaskExecutor() 开启一个新的线程

2、计算完成时的回调方法

1)thenAccept 消费处理结果
接受任务的处理结果,并消费处理,无返回结果

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);

@FunctionalInterface public interface Consumer<T> { void accept(T t); }

2)其余方法,慢慢引入…请持续关注哦

二、举例:异步获取随机数值

第一步:创建异步执行任务

CompletableFuture<T> completableFuture = CompletableFuture.supplyAsync( //执行逻辑 );

入参:Supplier是函数式接口
@FunctionalInterface public interface Supplier<T> { T get(); }

第二步:异步任务执行完成回调

completableFuture.thenAccept(result -> { //回收结果 });
thenAccept接收的是Consumer类型的函数
@FunctionalInterface public interface Consumer<T> { void accept(T t); }

第三步:异步执行任务异常

completableFuture.exceptionally(e -> { //异常处理 });

完整代码展示:

import java.util.concurrent.CompletableFuture;

public class CompletableFutureDemo {

public static void main(String[] args) throws InterruptedException{
    //创建异步执行任务
    CompletableFuture<Double> completableFuture = CompletableFuture.supplyAsync(CompletableFutureDemo::getValue);
    //如果执行成功
    completableFuture.thenAccept(result -> System.out.println("result = " + result));
    //如果执行异常
    completableFuture.exceptionally(e ->{
        e.printStackTrace();
        return 0.0d;
    });
    Thread.sleep(1000);
}

public static Double getValue() {
    try {
        Thread.sleep(300);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if (Math.random() < 0.1) {
        throw new RuntimeException("value < 0.1");
    }
    return Math.random();
}
}

第四步:执行结果:

1、正常情况

在这里插入图片描述
2、异常情况
在这里插入图片描述

  • 下一节讲解CompletableFuture的串行执行
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值