Java CompletableFuture.acceptEither()方法介绍

x33g5p2x  于2022-09-24 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(191)

Java CompletableFuture 实现了 CompletionStageFuture 接口。 CompletableFuture.acceptEither 继承自 CompletionStageacceptEither 方法返回一个新的 CompletionStage,当这个或另一个给定阶段正常完成时,将使用相应的结果作为所提供操作的参数来执行。
从 Java 文档中找到 acceptEither 方法的方法声明。

CompletionStage<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)

参数other 是另一个CompletionStage
参数 action 是在完成返回的 CompletionStage 之前要执行的操作。
查找示例。
示例 1
AcceptEitherDemo1.java

package com.concretepage;
import java.util.concurrent.CompletableFuture;
public class AcceptEitherDemo1 {
  public static void main(String[] args) {
     CompletableFuture.supplyAsync(() -> "Welcome ABC")
        .acceptEither(CompletableFuture.supplyAsync(() -> "Welcome XYZ"), s -> System.out.println(s));
  }
}

输出

Welcome ABC

正如我们所知,acceptEither 方法是使用此阶段或其他给定阶段的结果执行的,以较早正常完成的为准。所以在我们的例子中,有时输出是“Welcome ABC”,有时输出是“Welcome XYZ”。
示例 2
AcceptEitherDemo2.java

package com.concretepage;
import java.util.concurrent.CompletableFuture;
public class AcceptEitherDemo2 {
  public static void main(String[] args) {
	
    CompletableFuture<String> cfuture = CompletableFuture.supplyAsync(() -> getA());
    
    CompletableFuture<String> otherCFuture = CompletableFuture.supplyAsync(() -> getB());
    
    CompletableFuture<Void> cf = cfuture.acceptEither(otherCFuture, s -> System.out.println(s));
    
    cf.join();
  }
  private static String getA() {
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        System.err.println(e);
    }	
	return "Mahesh";
  }
  private static String getB() {
    try {
      Thread.sleep(400);
  } catch (InterruptedException e) {
      System.err.println(e);
  }		
	return "Krishna";
  }  
}

输出

Krishna

在上面的示例中,我们可以看到 otherCFuture 将比 cfuture 更早完成,因为 getB() 将比 getA() 方法更早完成。因此,acceptEither 方法将使用 otherCFuture 完成阶段的结果执行。

相关文章

微信公众号

最新文章

更多