自定义线程池异步批量处理任务

自定义线程池(单例模式)

package com.example.demo.ThreadPool;

import java.util.concurrent.*;


public class SyncGlobalThreadPool {

    private static class SingletonHolder {
        /*使用自定义线程池,7个参数依次代表
            1、核心线程数
            2、最大线程数
            3、超时等待时间
            4、时间单位
            5、允许等待的线程数
            6、执行工厂
            7、拒绝策略(这里使用拒绝后续线程并抛异常的策略)
         */
        private static ExecutorService threadPool = new ThreadPoolExecutor(
                5,
                5,
                30,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(20),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    public SyncGlobalThreadPool() {
    }

    /**
     * 单例模式创建全局线程池
     * @return 自定义全局线程池
     */
    public static ExecutorService getInstance() {
        return SingletonHolder.threadPool;
    }
}

使用线程池异步处理任务

  • 定义线程类 BuildFileThread,执行业务逻辑。需要传入CountDownLatch
  • 使用CountDownLatch 等待所有线程执行完,再继续执行主线程
package com.example.demo.ThreadPool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

public class test {

    public  void x() {
        //线程池10个线程
        ExecutorService executorService = SyncGlobalThreadPool.getInstance();
        List<Long> ids = Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L);
        //记录任务执行时间
        long t1 = System.currentTimeMillis();
        CountDownLatch c=new CountDownLatch(ids.size());
        //循环id组
        Iterator<Long> it = ids.iterator();
        while (it.hasNext()) {
            executorService.submit(new BuildFileThread(it.next(),c));
        }
        try {
            c.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long t2 = System.currentTimeMillis();
        System.out.println("执行时间:" + (t2 - t1) / 1000+"s");
        executorService.shutdown();
    }

    class BuildFileThread implements  Runnable {

        long id;

        CountDownLatch c;

        public BuildFileThread(long id, CountDownLatch c) {
            this.id = id;
            this.c = c;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("id=" + id + "    线程" + Thread.currentThread().getName());
            c.countDown();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值