介绍

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方法返回响应结果。

源码阅读

依赖关系

Java核心复习——CompletableFuture

参考文档

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

关于作者

后端程序员,五年开发经验,从事互联网金融方向。技术公众号「清泉白石」。如果您在阅读文章时有什么疑问或者发现文章的错误,欢迎在公众号里给我留言。

Java核心复习——CompletableFuture

相关文章:

  • 2021-10-06
  • 2022-02-03
  • 2022-03-04
  • 2022-12-23
  • 2021-09-17
  • 2022-12-23
  • 2021-10-15
  • 2021-07-24
猜你喜欢
  • 2021-07-21
  • 2022-02-11
  • 2021-09-09
  • 2021-09-20
  • 2021-09-17
  • 2021-10-24
  • 2022-01-02
相关资源
相似解决方案