Java CompletableFuture.runAfterEither任何一个完成就执行Runnable
假设两个互不相干的任务A和B,只要任何一个完成就触发执行线程Runnable
private void test() {
CompletableFuture f1 = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
TimeUnit.SECONDS.sleep((int) (Math.random() * 10) + 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务A");
return "任务A";
}
});
f1.runAfterEither(CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
TimeUnit.SECONDS.sleep((int) (Math.random() * 10) + 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务B");
return "任务B";
}
}), new Runnable() {
@Override
public void run() {
System.out.println("run");
}
});
}
输出:
I/System.out: 任务A
I/System.out: run
I/System.out: 任务B