CompletableFuture常用方法

CompletableFuture常用方法

 

  • ①获得结果和触发计算
  •  

    • 获取结果
  •  

    •  

      • public T get()
      • public T get(long timeout,TimeUnit unit)
      • public T join() --->和get一样的作用,只是不需要抛出异常
      • public T getNow(T valuelfAbsent) --->计算完成就返回正常值,否则返回备胎值(传入的参数),立即获取结果不阻塞
  •  

    • 主动触发计算
  •  

    •  

      • public boolean complete(T value) ---->是否打断get方法立即返回括号值

 

 

  • ②对计算结果进行处理
  •  

    • thenApply --->计算结果存在依赖关系,这两个线程串行化---->由于存在依赖关系(当前步错,不走下一步),当前步骤有异常的话就叫停
    • handle --->计算结果存在依赖关系,这两个线程串行化---->有异常也可以往下走一步
    • /**
    •  * @author Guanghao Wei
    •  * @create 2023-04-10 13:43
    •  */
    • public class CompletableFutureApiDemo {
    •     public static void main(String[] args) throws
      ExecutionException, InterruptedException, TimeoutException {
    •         ExecutorService threadPool =
      Executors.newFixedThreadPool(3);
    •         CompletableFuture<Integer> completableFuture =
      CompletableFuture.supplyAsync(() -> {
    •             try {
    •                
      TimeUnit.SECONDS.sleep(1);
    •             } catch (InterruptedException e) {
    •                 e.printStackTrace();
    •             }
    •             return 1;
    •         }, threadPool).thenApply(f -> {
    •             System.out.println("222");
    •             return f + 2;
    •         }).handle((f, e) -> {
    •             System.out.println("3333");
    •             int i=10/0;
    •             return f + 2;
    •  
    • //             thenApply(f -> {
    • //            System.out.println("3333");
    • //            return f + 2;
    •         }).whenComplete((v, e) -> {
    •             if (e == null) {
    •                
      System.out.println("----计算结果" + v);
    •             }
    •         }).exceptionally(e -> {
    •             e.printStackTrace();
    •             System.out.println(e.getCause());
    •             return null;
    •         });
    •        
      System.out.println(Thread.currentThread().getName() + "------主线程先去做其他事情");
    •     }
    • }

 

  • ③对计算结果进行消费
  •  

    •  

      • thenRun(Runnable runnable) :任务A执行完执行B,并且不需要A的结果
      • thenAccept(Consumer action): 任务A执行完执行B,B需要A的结果,但是任务B没有返回值
      • thenApply(Function fn): 任务A执行完执行B,B需要A的结果,同时任务B有返回值

 

/**

 * @author Guanghao Wei

 * @create 2023-04-10 13:59

 */

public class CompletableFutureApi2Demo {

    public static void main(String[] args) {

        System.out.println(CompletableFuture.supplyAsync(()
-> "result").thenRun(() -> {}).join());//null

        System.out.println(CompletableFuture.supplyAsync(()
-> "result").thenAccept(r -> System.out.println(r)).join());//result null

        System.out.println(CompletableFuture.supplyAsync(()
-> "result").thenApply(f -> f + 2).join());//result2

    }

}

 

  •  
    • CompletableFuture的Async后缀方法和线程池说明
  •  

    •  

      • 如果没有传入自定义线程池,都用默认线程池ForkJoinPool
      • 传入一个线程池,如果你执行第一个任务时,传入了一个自定义线程池
  •  

    •  

      •  

        • 调用thenRun方法执行第二个任务时,则第二个任务和第一个任务时共用同一个线程池
        • 调用thenRunAsync执行第二个任务时,则第一个任务使用的是你自定义的线程池,第二个任务使用的是ForkJoin线程池
  •  

    •  

      • 备注:可能是线程处理太快,系统优化切换原则,
        直接使用main线程处理,thenAccept和thenAcceptAsync,thenApply和thenApplyAsync等,之间的区别同理。

 

 

  • ④对计算速度进行选用
  •  

    • 谁快用谁
    • applyToEither
    • /**
    •  * @author Guanghao Wei
    •  * @create 2023-04-10 14:11
    •  * 可以合并写在一起,不必拆分
    •  */
    • public class CompletableFutureApiDemo {
    •     public static void main(String[] args) {
    •         ExecutorService threadPool =
      Executors.newFixedThreadPool(3);
    •         CompletableFuture<String> playA =
      CompletableFuture.supplyAsync(() -> {
    •             try {
    •                
      System.out.println("A come in");
    •                
      TimeUnit.SECONDS.sleep(2);
    •             } catch (InterruptedException e) {
    •                 e.printStackTrace();
    •             }
    •             return "playA";
    •         }, threadPool);
    •  
    •  
    •         CompletableFuture<String> playB =
      CompletableFuture.supplyAsync(() -> {
    •             try {
    •                
      System.out.println("B come in");
    •                
      TimeUnit.SECONDS.sleep(3);
    •             } catch (InterruptedException e) {
    •                 e.printStackTrace();
    •             }
    •             return "playB";
    •         }, threadPool);
    •  
    •         CompletableFuture<String> result =
      playA.applyToEither(playB, f -> {
    •             return f + " is winner";
    •         });
    •  
    •         /**
    •          * A come in
    •          * B come in
    •          * main-----------winner:playA is winner
    •          */
    •        
      System.out.println(Thread.currentThread().getName() + "-----------winner:" +
      result.join());
    •     }
    • }

 

  • 对计算结果进行合并
  •  

    • 两个CompletableStage任务都完成后,最终能把两个任务的结果一起交给thenCombine来处理
    • 先完成的先等着,等待其他分支任务
    • /**
    •  * @author Guanghao Wei
    •  * @create 2023-04-10 14:28
    •  * 可以合并写在一起,不必拆分
    •  */
    • public class CompletableFutureApi3Demo {
    •     public static void main(String[] args) {
    •         CompletableFuture<Integer> completableFuture1
      = CompletableFuture.supplyAsync(() -> {
    •            
      System.out.println(Thread.currentThread().getName() + " 启动");
    •             try {
    •                
      TimeUnit.SECONDS.sleep(1);
    •             } catch (InterruptedException e) {
    •                 e.printStackTrace();
    •             }
    •             return 10;
    •         });
    •  
    •         CompletableFuture<Integer> completableFuture2
      = CompletableFuture.supplyAsync(() -> {
    •            
      System.out.println(Thread.currentThread().getName() + " 启动");
    •             try {
    •                
      TimeUnit.SECONDS.sleep(2);
    •             } catch (InterruptedException e) {
    •                 e.printStackTrace();
    •             }
    •             return 20;
    •         });
    •  
    •         CompletableFuture<Integer> finalResult =
      completableFuture1.thenCombine(completableFuture2, (x, y) -> {
    •            
      System.out.println("----------开始两个结果合并");
    •             return x + y;
    •         });
    •         System.out.println(finalResult.join());
    •  
    •     }
    • }
posted @ 2025-10-09 16:03  扛着音响去化缘  阅读(7)  评论(0)    收藏  举报
Sakana Widget右下角定位