带有 void 方法的 CompletableFuture
CompletableFuture with void methods
我正在寻找 运行 两种方法 a()
和 b()
不接受参数并且 return 不接受任何参数(即 void 方法)的异步方法,这样它们是return同时以任意顺序编辑。
但是,第三种方法 c()
应该仅在上述任一其他方法完成后 运行。
我相信我应该创建两个 CompletableFuture 对象(a()
的 cf1 和 b()
的 cf2),然后使用 CompletableFuture.anyOf(cf1, cf2).join()
来阻止 c()
的代码。
但是,我不确定如何创建 cf1 和 cf2 CompletableFuture 对象。我了解 a()
和 b()
方法本质上类似于 Runnable 的 run
方法,但我不想更改它们的实现方式。我应该调用 CompletableFuture 的哪个方法来为这两个方法创建这个 CompletableFuture 对象?
非常感谢您的帮助!
如果我正确理解你的问题,你可以做这样的事情来等待方法 a()
或 b()
中的任何一个完成,然后一旦其中一个完成,你 运行方法c()
.
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> a());
CompletableFuture<Void> cf2 = CompletableFuture.runAsync(() -> b());
CompletableFuture<Void> cf3 = CompletableFuture.anyOf(cf1, cf2).thenRunAsync(() -> c());
或者你可以直接用runAfterEither
这样
CompletableFuture<Void> a = CompletableFuture.runAsync(() -> {
Util.delay(new Random().nextInt(1000));
System.out.println("Hello ");
});
a = a.runAfterEither(CompletableFuture.runAsync(() -> {
Util.delay(new Random().nextInt(1000));
System.out.println("Hi ");
}), () -> {
System.out.println("world"); // your c();
});
a.join();
我正在寻找 运行 两种方法 a()
和 b()
不接受参数并且 return 不接受任何参数(即 void 方法)的异步方法,这样它们是return同时以任意顺序编辑。
但是,第三种方法 c()
应该仅在上述任一其他方法完成后 运行。
我相信我应该创建两个 CompletableFuture 对象(a()
的 cf1 和 b()
的 cf2),然后使用 CompletableFuture.anyOf(cf1, cf2).join()
来阻止 c()
的代码。
但是,我不确定如何创建 cf1 和 cf2 CompletableFuture 对象。我了解 a()
和 b()
方法本质上类似于 Runnable 的 run
方法,但我不想更改它们的实现方式。我应该调用 CompletableFuture 的哪个方法来为这两个方法创建这个 CompletableFuture 对象?
非常感谢您的帮助!
如果我正确理解你的问题,你可以做这样的事情来等待方法 a()
或 b()
中的任何一个完成,然后一旦其中一个完成,你 运行方法c()
.
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> a());
CompletableFuture<Void> cf2 = CompletableFuture.runAsync(() -> b());
CompletableFuture<Void> cf3 = CompletableFuture.anyOf(cf1, cf2).thenRunAsync(() -> c());
或者你可以直接用runAfterEither
这样
CompletableFuture<Void> a = CompletableFuture.runAsync(() -> {
Util.delay(new Random().nextInt(1000));
System.out.println("Hello ");
});
a = a.runAfterEither(CompletableFuture.runAsync(() -> {
Util.delay(new Random().nextInt(1000));
System.out.println("Hi ");
}), () -> {
System.out.println("world"); // your c();
});
a.join();