CompletableFuture的applyToEitherAsync:最快返回输出的线程结果作为下一次任务的输入
applyToEitherAsync和附录1的acceptEitherAsync类似,只是说acceptEitherAsync是对结果的消费,而applyToEitherAsync则是把最快返回的计算输出结果,再利用起来作为下一次线程任务的输入。
private void test() { System.out.println("开始..."); CompletableFuture.supplyAsync(new Supplier<String>() { @Override public String get() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("返回 A"); return "A"; } }).applyToEitherAsync(CompletableFuture.supplyAsync(new Supplier<String>() { @Override public String get() { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("返回 B"); return "B"; } }), new Function<String, Object>() { @Override public Object apply(String s) { return s + " 最快返回"; } }).whenCompleteAsync(new BiConsumer<Object, Throwable>() { @Override public void accept(Object o, Throwable throwable) { System.out.println(o.toString()); } }); }
运行结果输出:
07-02 15:17:41.941 10883-10883/zhangphil.test I/System.out: 开始...
07-02 15:17:42.946 10883-10921/zhangphil.test I/System.out: 返回 A
07-02 15:17:42.949 10883-10943/zhangphil.test I/System.out: A 最快返回
07-02 15:17:46.946 10883-10922/zhangphil.test I/System.out: 返回 B
附:
1,《CompletableFuture的acceptEitherAsync:哪个线程跑的最快用那个》链接:https://blog.csdn.net/zhangphil/article/details/80883953