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

使用多线程的方式对数据操作

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

使用多线程的方式对数据操作

分享知识 传递快乐

使用多线程的方式批量处理数据操作。示例如下:

@Test
public void syncAccount() throws Exception {
    // 每500条数据开启一条线程
    int threadSize = 50;
    // 总数据条数
    int dataSize = readAll.size();
    // 方法一:每个线程处理数据量
    int threadNum = dataSize / threadSize + 1;
    if (dataSize % threadSize == 0) {
        threadNum = threadNum - 1;
    }
    // 方法一:每个线程处理数据量
    // int threadNum = (threadSize - 1) / threadSize + 1;

    // 初始化线程池
    ExecutorService executorService = new ThreadPoolExecutor(threadNum,// 核心线程池大小
            100,// 线程池最大容量大小
            0L,// 线程池空闲时,线程存活的时间
            TimeUnit.MILLISECONDS,// 时间单位
            new linkedBlockingQueue()// 任务队列
    );

    List>>> tasks = this.multiThread(threadSize, threadNum, dataSize, readAll);

    List>>> results = executorService.invokeAll(tasks);

    for (Future>> future : results) {
        //每个线程返回的数据处理,有顺序对应关系
//            System.out.println(future.get());
        writeList.addAll(future.get());
    }

    // 关闭线程池
    executorService.shutdown();
    System.out.println("线程任务执行结束");
}


private List>>> multiThread(int threadSize, int threadNum, int dataSize, List> excelList) {
    // 定义一个任务集合
    List>>> tasks = new ArrayList>>>();
    Callable>> task = null;
    List> cutExcelList = null;

    for (int i = 0; i < threadNum; i++) {
        // 确定每条线程的数据
        if (i == threadNum - 1) {
            cutExcelList = excelList.subList(threadSize * i, dataSize);
        } else {
            cutExcelList = excelList.subList(threadSize * i, threadSize * (i + 1));
        }
//            System.out.println("第" + (i + 1) + "组:" + cutExcelList.toString());
        final List> cutList = cutExcelList;
        task = new Callable>>() {

            @Override
            public List> call() throws Exception {
                // 线程处理逻辑
//                    System.out.println(Thread.currentThread().getName() + "线程:" + cutList);
//                    return Thread.currentThread().getName();
                return sendSyncCenter(Thread.currentThread().getName(), cutList);
            }
        };
        // 这里提交的任务容器列表和返回的Future列表存在顺序对应的关系
        tasks.add(task);
    }

    return tasks;
}

private List> sendSyncCenter(String threadName, List> excelList) {
    List> writeList = new ArrayList<>();
    for (Map row : excelList) {

        row.put("threadName", threadName);

        writeList.add(row);
    }
    return writeList;
}

 —————————
如有不足请留言指正
相互学习,共同进步

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

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

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