JDK8-11-CompletableFuture(8)- applyToEither 方法使用
生活中有这样的场景,当坐公交去某个地方时,一般都会有多种线路选择,通常人们在等待到指定线路公交时就会上车,例如:
张三下班后坐公交回家,可以选择 539 路和 906 路,当其中有一辆公交到达,张三就选择坐这辆车回家,这种场景可以使用 applyToEither 方法,用程序模拟如下:
import java.util.concurrent.CompletableFuture;
public class ApplyToEitherTest {
public static void main(String[] args) {
PrintTool.printTimeAndThread("张三下班准备回家。。。");
PrintTool.printTimeAndThread("张三等待906,539公交。。。");
CompletableFuture<String> busCF = CompletableFuture.supplyAsync(() -> {
PrintTool.printTimeAndThread("906 路公交在路上。。。");
PrintTool.sleep(5000);
return "906";
}).applyToEither(CompletableFuture.supplyAsync(() -> {
PrintTool.printTimeAndThread("539 路公交在路上。。。");
PrintTool.sleep(4000);
return "539";
}), first -> first + "路公交");
PrintTool.printTimeAndThread("张三坐上" + busCF.join());
}
}
运行结果如下:
1666411943231 | 1 | main | 张三下班准备回家。。。
1666411943231 | 1 | main | 张三等待906,539公交。。。
1666411943360 | 14 | ForkJoinPool.commonPool-worker-1 | 906 路公交在路上。。。
1666411943361 | 15 | ForkJoinPool.commonPool-worker-2 | 539 路公交在路上。。。
1666411947367 | 1 | main | 张三坐上539路公交
906路公交与539公交同时行驶在路上,没有先后顺序,906路耗时 5000,539路耗时4000,显然539路先到达,最终 busCF.join 返回结果为 “539路公交”,可见 applyToEither 方法作用是返回两个任务中最先完成的任务结果