Spring - 如何运行一系列线程并等待它们完成再完成?



目前我有这段代码,我想使用内置的Spring功能。我正在使用@Async作为我不关心的方法,当它完成时。有没有办法使用它,但等到池中的那些线程完成?

Runnable thread = () -> {
for (String date : dates) {
Path dir = Paths.get(primaryDisk, partition, folder, date);
File tmp = dir.toFile();
deleteDir(tmp);

}
};
executor.submit(thread);

稍后在函数中,我使用以下代码等待它们完成。

executor.shutdown();
try {
executor.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}

如果你使用弹簧,你可以使用这样的东西

public void doSomething(Set<String> emails){
CompletableFuture.allOf(emails.stream()
.map(email -> yourService.doAsync(email)
.exceptionally(e -> {
LOG.error(e.getMessage(), e);
return null;
})
.thenAccept(longResult -> /*do something with result if needed */))
.toArray(CompletableFuture<?>[]::new))
.join();
}

此代码将启动其他线程中的每个 doAsync 方法调用,并等待所有这些任务完成。

您的异步方法

@Async
public CompletableFuture<Long> doAsync(String email){
//do something
Long result = ...
return CompletableFuture.completedFuture(result);
}

如果你的doSomething方法和doAsync方法在同一个服务类中,你应该自注入你的服务

@Autowired
@Lazy
private YourService yourService

并通过此自注入引用(弹簧代理(调用您的@Async方法

yourService.doAsync(email)

以异步运行它。

最新更新