【工具类】CompletableFuture 使用详解

邓敏 2021年06月09日 88次浏览

runAsync和supplyAsync方法,这个两个方法为CompletableFuture的主要使用方式,其主要作用给任务提供异步线程的操作方式

如何使用
CompletableFuture 提供了四个静态方法来创建一个异步操作。

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)

其中:
runAsyn方法不支持返回值

public class CompletableFutureTest02 {

    public CompletableFuture Test(){
        CompletableFuture future  = CompletableFuture.runAsync(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(">>>>print.."+i);
            }
        });
        return future;
    }


    public static void main(String[] args) {
        CompletableFutureTest02 test02 = new CompletableFutureTest02();
        test02.Test().join();
    }
}

supplyAsync可以支持返回值

public class CompletableFutureTest {
    public Integer Test() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return 1;
        });

        CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(()->{

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return 1;
        });

        //使用get方法来获取返回值
        return future.get()+future01.get();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFutureTest test = new CompletableFutureTest();

        Long begin = System.currentTimeMillis();
        System.out.println(">>>>>>>begin"+begin);
        /*
        在执行Test()方法是会启动future和future01两个线程
        并且两个线程执行完毕后获取到结果值才代表Test()方法执行结束
         */
        
        System.out.println(test.Test());
        Long end = System.currentTimeMillis();
        Long exec = end-begin;
        System.out.println(">>>>>>>end"+end+">>>>>>exec"+exec);
    }
}

计算结果完成时的回调方法

当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:

public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)

参考:CompletableFuture 使用详解