JAVA多线程执行结果汇总,多线程执行,将结果汇总后返回给主线程

今天我在发布一个JAVA实用的多线执行结果汇总工具类,如果有改进的地方记得给我留言哟,谢谢大家的支持!最下面的测试代码!

/**
 * 多线程执行结果汇总工具
 *
 * @author 张帅
 * @date 2021年05月20日 11时28分02秒
 * @version V1.0
 * 
 * @param <T>
 */
@Slf4j
public class MultiFutureThread<T> {

    // 总线程数量
    private int threadSize;
    // 单次执行多少次线程
    private int singleSize;
    
    private List<Callable<T>> callableList = Lists.newArrayList();
    
    /**
     * 多线程执行结果汇总工具 构造方法
     * @param threadSize  总线程数量
     * @param singleSize  单次执行多少次线程
     */
    public MultiFutureThread(int threadSize, int singleSize) {
        super();
        this.threadSize = threadSize;
        this.singleSize = singleSize < 1 ? threadSize : singleSize;
    }

    /**
     * 设计要执行的程序段
     * 
     * @Title: setCallable
     * @param @param callable
     * @param @return 参数
     * @return MultiFutureThread<T> 返回类型
     * @throws
     */
    public MultiFutureThread<T> setCallable(Callable<T> callable) {
        if (callable != null) {
            callableList.add(callable);
        }
        return this;
    }

    /**
     * 运行线程
     * 
     * @Title: exec
     * @param @return 参数
     * @return List<T> 返回类型
     * @throws
     */
    public List<T> exec() {
        
        // 如果开启的线程数量为1时,刚不开启线程
        List<T> list = Lists.newArrayList();
        if (singleSize <= 1) {
            callableList.forEach(e -> {
                try {
                    T dataList = e.call();
                    list.add(dataList);
                } catch (Exception e1) {
                }
            });
            return list;
        }
        
//        ExecutorService executor = Executors.newFixedThreadPool(singleSize);
        ExecutorService executor = Executors.newCachedThreadPool();
        List<Future<T>> pointTaskFutureList = new ArrayList<>(singleSize);
        int total = threadSize; // 总计算结果
        int done = 0; //完成任务的数量
        try {
            int count = (total / singleSize) + 1;
            for(int j = 0; j < count; j++) {
                int index = j * singleSize;
                int endIndex = index + singleSize;
                int runSize = callableList.size() > endIndex ? endIndex : callableList.size();
                for (int i = index; i < runSize; i++) {
                    // 提交任务,任务的执行由线程池去调用执行并管理。
                    // 这里获取结果任务的Future,并放到list中,供所有任务提交完后,通过每个任务的Future判断执行状态和结果。
                    Future<T> future = executor.submit(callableList.get(i));
                    pointTaskFutureList.add(future);
                }
            
                while (!pointTaskFutureList.isEmpty()) {
                    Iterator<Future<T>> iter = pointTaskFutureList.iterator();
                    while (iter.hasNext()) {
                        Future<T> next = iter.next();
                        if (next.isDone()) {
                            done++;
                            T dataList = next.get();
                            list.add(dataList);
                            iter.remove();
                        }
                    }
                    log.info("总任务量:{},已完成任务量:{}", total, done);
                    // 停留一会,避免一直循环。
                    Thread.sleep(10);
                }
            }
            log.info("总任务量:{},完成任务量:{}", total, done);
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        } finally {
            executor.shutdown();
            try {
                executor.awaitTermination(1, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                log.error("线程超时,中断异常{}", e);
            }
        }
        
        return list;
    }
    
    /**
     * 测试
     * @Title: main
     * @param @param args
     * @param @throws Exception 参数
     * @return void 返回类型
     * @throws
     */
    public static void main(String[] args) throws Exception {
        MultiFutureThread<Integer> thread = new MultiFutureThread<Integer>(10, 10);
        for (int i = 0; i < 10; i++) {
            thread.setCallable(() -> {
                for(int j=0;j<10000;j++) {
                    System.out.println(new Random().nextInt() + "----------");
                }
                return new Random().nextInt();
            });
        }
        List<Integer> list = thread.exec();
        list.forEach(System.out::println);
    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值