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

Dyl*_*lan 3 java spring multithreading asynchronous spring-boot

目前我有这段代码,我想使用内置的 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);
Run Code Online (Sandbox Code Playgroud)

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

 executor.shutdown();

            try {
                executor.awaitTermination(5, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
Run Code Online (Sandbox Code Playgroud)

Jan*_*eXQ 5

如果你使用 spring 你可以使用这样的东西

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();
    }
Run Code Online (Sandbox Code Playgroud)

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

你的 doAsync 方法

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

如果您的 doSomething 方法和 doAsync 方法位于同一服务类中,您应该自我注入您的服务

@Autowired
@Lazy
private YourService yourService
Run Code Online (Sandbox Code Playgroud)

并通过这个自注入引用(spring代理)调用你的@Async方法

yourService.doAsync(email)
Run Code Online (Sandbox Code Playgroud)

真正异步运行它。