Java核心复习——CompletableFuture

介绍

JDK1.8引入CompletableFuture类。

使用方法


public class CompletableFutureTest {

    private static ExecutorService threadPool = new ThreadPoolExecutor(40, 100,
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(20));

    public String B() {
        System.out.println("执行方法B");
        sleep(5);
        return "Function B";
    }

    public String C() {
        System.out.println("执行方法C");
        sleep(20);
        return "Function C";
    }


    public void sleep(int i) {
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void testCompableFuture() {
        CompletableFuture<String> future;
        try {
            //Returns a new CompletableFuture 
            // that is asynchronously completed by a task running in the given executor 
            // with the value obtained by calling the given Supplier.
            future = CompletableFuture.supplyAsync(() -> B(), threadPool);
            //若去掉线程池,有何区别future = CompletableFuture.supplyAsync(() -> B());

            sleep(9);
            System.out.println(future.toString());
            System.out.println(future.isDone());
        } catch (RejectedExecutionException e) {
            System.out.println("调用搜索列表服务线程满负荷, param:{}");
        }
    }

    public static void main(String[] args) {
        CompletableFutureTest test = new CompletableFutureTest();
        test.testCompableFuture();
    }

}

API

supplyAsync方法

JDK方法描述

/**
     * Returns a new CompletableFuture that is asynchronously completed
     * by a task running in the given executor with the value obtained
     * by calling the given Supplier.
     *
     * @param supplier a function returning the value to be used
     * to complete the returned CompletableFuture
     * @param executor the executor to use for asynchronous execution
     * @param <U> the function's return type
     * @return the new CompletableFuture
     */
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                       Executor executor) {
        return asyncSupplyStage(screenExecutor(executor), supplier);
    }

应用场景

请求A的执行方法X,需满足下列需求:

①请求B、C、D中任一一个请求有返回结果,则X方法返回响应结果。

②请求B、C、D中都执行完,则X方法返回响应结果。

源码阅读

依赖关系

在这里插入图片描述

参考文档

JDK API文档
20 个使用 Java CompletableFuture的例子

原文地址:https://www.cnblogs.com/fonxian/p/10854651.html