栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021-10-14使用CountDownLatch多线程执行任务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-14使用CountDownLatch多线程执行任务

使用CountDownLatch多线程执行任务
  • 介绍
  • 使用CountDownLatch多线程执行任务

介绍

首先我是很抗拒使用java单进程去做这些批量任务处理(hadoop生态除外,超大数据的领头老大),或者做一写简单的etl工作,但是耐不住还是会有人要求使用java做一些批量任务。如下是CountDownLatch的一个简单工具类

使用CountDownLatch多线程执行任务
package info.lostmylife;

import org.apache.commons.collections.CollectionUtils;

import java.util.linkedList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;


public class BatchThreadUtils {

    private final static int MAX_THREAD_POOL = 10;

    private static final ExecutorService executorService = Executors.newFixedThreadPool(MAX_THREAD_POOL);

    public interface ThreadInterface {

        
        Object run() throws InterruptedException;
    }


    
    public static synchronized List executor(List runnableList) throws Exception {
        if (CollectionUtils.isEmpty(runnableList) || runnableList.size() > MAX_THREAD_POOL) {
            throw new RuntimeException("任务列表不允许为空, 且不允许大于" + MAX_THREAD_POOL);
        }

        CountDownLatch countDownLatch = new CountDownLatch(runnableList.size());
        List> results = new linkedList<>();

        for (ThreadInterface runnable : runnableList) {
            Future submit = executorService.submit(() -> {
                try {
                    return runnable.run();
                } finally {
                    countDownLatch.countDown();
                }
            });
            results.add(submit);
        }
        countDownLatch.await();
        return results.stream().map(i -> {
            try {
                return i.get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
    }

    
    public static void shutdown() {
        executorService.shutdown();
    }


    public static void main(String[] args) throws Exception {
        List runnableList = new linkedList<>();
        for (int i = 0; i < MAX_THREAD_POOL; i++) {
            int finalI = i;
            runnableList.add(() -> finalI);
        }
        List executor = executor(runnableList);
        System.out.println(executor);
        shutdown();
    }

}



转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号