CompletableFuture多线程处理任务,等待所有线程处理完并返回结果

CompletableFuture多线程处理任务,等待所有线程处理完并返回结果

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

/**
 * @Description:
 * @Author: Alun
 * @Date: 2023/12/21 19:43
 * @Version: V1.0
 */
public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("=============开始==============");
        long start = System.currentTimeMillis();
        List<CompletableFuture<String>> allCompletableFuture = new ArrayList<>();
        // 线程池
        ExecutorService executor = Executors.newWorkStealingPool(10);
        for (int i = 0; i < 100; i++) {
            int finalI = i+1;
            // 异步线程
            CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
                String str = task(finalI);
                return str;
            }, executor);
            allCompletableFuture.add(completableFuture);
        }

        // 等待所有线程执行结束
        System.out.println(allCompletableFuture.size());
        for (CompletableFuture<String> stringCompletableFuture : allCompletableFuture) {
            String str = stringCompletableFuture.get();
            System.out.println("=====结果====" + str);
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("=============结束==============");
        System.out.println(String.format("总耗时%s毫秒", time));
    }

    private static String task(Integer taskId) {
        int time = 1000;
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String str = String.format("任务号: %s, 执行时间: %s 毫秒", taskId, time);
        System.out.println("=====任务====" + str);
        return str;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值