JDK8-11-CompletableFuture(8)- applyToEither 方法使用

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 方法作用是返回两个任务中最先完成的任务结果

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值