|
@@ -0,0 +1,40 @@
|
|
|
|
|
+package space.anyi;
|
|
|
|
|
+
|
|
|
|
|
+import java.util.concurrent.CompletableFuture;
|
|
|
|
|
+
|
|
|
|
|
+public class Cf04_ThenEither {
|
|
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
|
|
+ // 场景: 数据优先读本地缓存(快),缓存没就等远程(慢),
|
|
|
|
|
+ // 谁先返回就用谁,避免干等最慢的那一路
|
|
|
|
|
+ CompletableFuture<String> cache = CompletableFuture.supplyAsync(() -> {
|
|
|
|
|
+ sleep(100);
|
|
|
|
|
+ return "缓存数据";
|
|
|
|
|
+ });
|
|
|
|
|
+ CompletableFuture<String> remote = CompletableFuture.supplyAsync(() -> {
|
|
|
|
|
+ sleep(400);
|
|
|
|
|
+ return "远程数据";
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ // applyToEither: 谁先完成用谁的结果,并继续用 BiFunction 加工
|
|
|
|
|
+ CompletableFuture<String> result = cache.applyToEither(remote, data -> "优先使用 -> " + data);
|
|
|
|
|
+ System.out.println("applyToEither 结果: " + result.join());
|
|
|
|
|
+
|
|
|
|
|
+ // acceptEither: 谁先完成消费谁的结果,无返回值
|
|
|
|
|
+ CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> { sleep(50); return "A"; });
|
|
|
|
|
+ CompletableFuture<String> b = CompletableFuture.supplyAsync(() -> { sleep(400); return "B"; });
|
|
|
|
|
+ a.acceptEither(b, s -> System.out.println("acceptEither 选中了先完成的: " + s)).join();
|
|
|
|
|
+
|
|
|
|
|
+ // runAfterEither: 谁先完成都行,等时间点即可,不关心数据
|
|
|
|
|
+ CompletableFuture<Void> r1 = CompletableFuture.runAsync(() -> sleep(60));
|
|
|
|
|
+ CompletableFuture<Void> r2 = CompletableFuture.runAsync(() -> sleep(500));
|
|
|
|
|
+ r1.runAfterEither(r2, () -> System.out.println("runAfterEither: 有一路先完成了")).join();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static void sleep(long ms) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ Thread.sleep(ms);
|
|
|
|
|
+ } catch (InterruptedException e) {
|
|
|
|
|
+ e.printStackTrace();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|