CompletableFuture

CompletableFuture是由Java 8引入的,在Java8之前我们一般通过Future实现异步。

  • Future用于表示异步计算的结果,只能通过阻塞或者轮询的方式获取结果,而且不支持设置回调方法,Java 8之前若要设置回调一般会使用guava的ListenableFuture,回调的引入又会导致臭名昭著的回调地狱。
  • CompletableFuture对Future进行了扩展,可以通过设置回调的方式处理计算结果,同时也支持组合操作,支持进一步的编排,同时一定程度解决了回调地狱的问题。

依赖一个cf

thenApply

ExecutorService executor = Executors.newFixedThreadPool(5);
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("执行step1");
            return "result1";
        }, executor);
        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("执行step2");
            return "result2";
        }, executor);

        CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("执行step3");
            return "result3";
        }, executor);
        
        CompletableFuture<String> cf4 = cf1.thenApply(result1 -> {
            System.out.println(result1);
            return "result4";
        });

依赖两个cf

thenCombine

 cf2.thenCombine(cf1, (result2, result1) -> {
            System.out.println(result1 + "," + result2);
            System.out.println("执行step4");
            return "step4 result";
        }).thenAccept(result4 -> System.out.println(result4));

依赖多个cf

allOf

CompletableFuture<Void> cf5 = CompletableFuture.allOf(cf1, cf2, cf3);
        CompletableFuture<String> result = cf5.thenApply(v -> {
            //这里的join并不会阻塞,因为传给thenApply的函数是在CF3、CF4、CF5全部完成时,才会执行 。
            String result1 = cf1.join();
            String result2 = cf2.join();
            String result3 = cf3.join();
            //根据result3、result4、result5组装最终result;
            return "result";
        });

你可能感兴趣的:(python,开发语言,后端,java,mysql,ide)