假设我有一个 Java 函数,它必须做很多工作。这项工作由几个不同的事情组成,它们在各自的函数中定义并且彼此独立。
void myFunction() {
foo();
bar();
}
但是,这些函数一个接一个地运行(就像我编写的代码一样),这在这里不是必需的,并且使整个函数运行的时间比必要的要长。在自己的线程中运行这两个函数需要更多的代码:
void myFunction() {
UncaughtExceptionHandler eh = (th, t) -> { throw new UndeclaredThrowableException(t); };
try {
Thread foo = new Thread(() -> foo());
Thread bar = new Thread(() -> bar());
foo.setUncaughtExceptionHandler(eh);
bar.setUncaughtExceptionHandler(eh);
foo.start();
bar.start();
foo.join();
bar.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
所以我想知道在较新的 Java 版本中是否有一些内置方法可以更有效地执行此操作,例如:
Threads.doParallel(
() -> foo(),
() -> bar()
);
最佳答案
我得到的最短的,使用 CompletableFutures 是这样的:
CompletableFuture.allOf(
CompletableFuture.runAsync(new FutureTask<Void>(() -> foo(), null)),
CompletableFuture.runAsync(new FutureTask<Void>(() -> bar(), null))
).get();
这在 foo()
或 bar()
中没有异常处理。但我们可以补充一点,牺牲一些简洁性:
CompletableFuture.allOf(
CompletableFuture.runAsync(new FutureTask<Void>(() -> foo(), null)),
CompletableFuture.runAsync(new FutureTask<Void>(() -> bar(), null))
)
.exceptionally(t -> {
throw new UndeclaredThrowableException(t);
})
.get();
关于java - 在 Java 中是否有并行调用多个函数的简写方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58408274/