任务批处理通用工具类

复制代码
package com.sxsoft.admin.utils;

import com.sxsoft.admin.entity.TIsp;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.function.Consumer;

/***
 * 任务批处理通用工具类
 */
public class TaskDisposeUtils {
    /**
     * 使用线程池批处理,当所有任务处理完毕后才会返回
     * @param taskList 任务列表
     * @param consumer 处理任务的方法
     * @param executor 线程池
     * @param <T>
     * @throws InterruptedException
     */
    public static <T> void dispose(List<T> taskList, Consumer<? super T> consumer, Executor executor){
        try {
            if (taskList == null || taskList.size() == 0) {
                return;
            }
            Objects.nonNull(consumer);
            CountDownLatch countDownLatch = new CountDownLatch(taskList.size());
            for (T item : taskList) {
                executor.execute(() -> {
                    try {
                        consumer.accept(item);
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        //任务列表
        List<String> taskList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            //模拟构建任务数据
            taskList.add("任务-" + i);
        }

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        //调用工具类批处理任务
        TaskDisposeUtils.dispose(taskList, TaskDisposeUtils::disposeTask, executorService);

        System.out.println("任务处理完毕,耗时(ms):" + (System.currentTimeMillis() - startTime));
        executorService.shutdown();
    }

    public static void disposeTask(String task) {
        System.out.println(String.format("【%s】处理成功", task));
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void disposeTask2(TIsp task) {
        System.out.println(String.format("【%s】处理成功2", task.getIspName()));
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
复制代码

 

posted on   五官一体即忢  阅读(9)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示