开启多线程批量处理数据

 public void deal() {
        //待处理集合
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }

        //定义线程池
        ExecutorService exec = new ThreadPoolExecutor(5, 10,
                100, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(10), new ThreadFactoryBuilder().setNameFormat("thread-pool-%d").build(), new ThreadPoolExecutor.AbortPolicy());

        // 假如我开启5条线程,计算每条线程处理多少条数据
        int onceNum = (int) Math.ceil((double) list.size() / 5);

        // 遍历开启5条线程
        for (int i = 0; i < 5; i++) {
            //为了在run方法中使用变量i的值,需要在这里重新定义
            int n = i;
            //定义线程任务
            Runnable task = () -> {
                try {
                    //遍历,计算当前需要处理的这批数据的角标
                    for (int j = onceNum * n; j < (onceNum * n + onceNum); j++) {
                        System.out.println(Thread.currentThread().getName() + "-----" + list.get(j));
                    }
                } catch (Exception e) {
                    log.error("多线程执行失败,原因:" + e.getMessage());
                }

                // 休息一下
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ignored) {
                    log.error("线程出错!");
                }
            };

            // 提交任务(开启线程)
            exec.submit(task);
        }
        // 关闭线程
        exec.shutdown();

        // 判断所有线程都结束
        while (true) {
            if (exec.isTerminated()) {
                log.info("-----------------所有的子线程都结束了!");
                break;
            }
            // 如果还有线程正在执行中,等待3秒再判断
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.error("线程出错!");
            }
        }

        //后续逻辑
        System.out.println("线程全部执行完成!");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值