使用 completablefuture 的 runaftereither 方法,可以在两个异步任务中任意一个完成时立即执行指定的无返回值操作。具体做法是调用其中一个 completablefuture 实例的 runaftereither 方法,传入另一个 completablefuture 作为竞争对象,并传入一个 runnable 作为回调逻辑。该操作不产生新的结果值,仅用于触发副作用,如日志记录或状态更新。

runAfterEither 与 thenAccept 的核心区别是什么
runAfterEither 与 thenAccept 的主要区别在于触发条件和返回值类型。thenAccept 仅在当前 CompletableFuture 完成时触发,且必须处理当前任务的结果;而 runAfterEither 在任一竞争任务完成时触发,且不接收任何参数,也不返回新值。这意味着 runAfterEither 适用于“谁先跑完谁就通知”的场景,而不关心具体是谁完成了,也不关心结果内容。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class RunAfterEitherDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> taskA = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) {}
return "Result A";
});
CompletableFuture<String> taskB = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(50); } catch (InterruptedException e) {}
return "Result B";
});
// 当 taskA 或 taskB 任意一个完成时,执行打印操作
taskA.runAfterEither(taskB, () -> {
System.out.println("One of the tasks finished. Current time: " + System.currentTimeMillis());
});
// 等待两个任务都真正完成,以确保主线程不会过早退出
String resultA = taskA.get();
String resultB = taskB.get();
System.out.println("Task A: " + resultA);
System.out.println("Task B: " + resultB);
}
}预期输出顺序可能因系统负载略有不同,但核心行为如下:控制台会先打印出包含时间戳的 “One of the tasks finished...” 消息(因为 taskB 较快),随后打印 “Task A: Result A” 和 “Task B: Result B”。这证明了回调是在任一任务完成后立即执行的,且不影响后续对结果的获取。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
立即学习“Java免费学习笔记(深入)”;
如果两个任务同时完成会发生什么
如果两个竞争任务几乎同时完成,runAfterEither 的回调仍然只会执行一次。JVM 内部的实现机制保证了即使多个任务在同一时刻达到完成状态,回调函数也只会被调度执行一次,避免重复触发。这种行为类似于原子操作,确保了副作用的唯一性。开发者无需在回调内部添加额外的锁或检查逻辑来防止重复执行。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
public class SimultaneousCompletionDemo {
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
int[] callCount = {0};
CompletableFuture<Void> taskA = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) {}
return null;
}).thenApply(v -> null);
CompletableFuture<Void> taskB = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) {}
return null;
}).thenApply(v -> null);
taskA.runAfterEither(taskB, () -> {
synchronized (callCount) {
callCount[0]++;
System.out.println("Callback executed. Count: " + callCount[0]);
}
latch.countDown();
});
latch.await();
System.out.println("Final count: " + callCount[0]);
}
}在上述代码中,两个任务被刻意设置为相同的延迟时间。运行结果显示,回调只被执行了一次,最终计数为 1。这验证了 runAfterEither 在处理并发完成场景下的原子性保证。即使任务 A 和任务 B 在同一毫秒内完成,回调也不会被多次调用,从而避免了资源浪费或状态不一致的问题。

















