等待执行完后一起收集的多线程

多线程执行

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
public class MyService {

    @Async
    public CompletableFuture<String> asyncMethod(int index) {
        // 异步执行的具体逻辑
        return CompletableFuture.completedFuture("Result " + index);
    }

    public void executeAsyncTasks() throws InterruptedException, ExecutionException {
        // 代码0
        System.out.println("执行异步前的逻辑代码0");

        List<CompletableFuture<String>> futures = new ArrayList<>();

        // 执行5次异步调用
        for (int i = 1; i <= 5; i++) {
            CompletableFuture<String> future = asyncMethod(i);
            futures.add(future);
        }

        // 等待所有异步任务完成并收集结果
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));

        // 获取所有异步任务的结果
        List<String> results = new ArrayList<>();
        allFutures.get(); // 等待所有任务完成
        for (CompletableFuture<String> future : futures) {
            results.add(future.get());
        }

        // 后续处理逻辑
        System.out.println("所有异步任务完成,结果为:" + results);
        // 执行代码2
    }
}

 

posted @ 2024-06-21 16:48  雪化山河  阅读(4)  评论(0编辑  收藏  举报