第一次写博客,大家多多支持,该系列是介绍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的串行执行