请给我一个List集合使用多线程的方式分批插入数据的Java代码

时间: 2023-03-13 20:06:08 浏览: 75
可以使用如下的Java代码来实现:List list = new ArrayList(); int maxThreadCount = 10; ExecutorService executorService = Executors.newFixedThreadPool(maxThreadCount); int batchSize = 1000; int listSize = list.size(); int threadCount = listSize/batchSize + (listSize%batchSize > 0 ? 1 : 0); for(int i=0; i<threadCount; i++){ int startIndex = i * batchSize; int endIndex = (i+1) * batchSize; endIndex = endIndex > listSize ? listSize : endIndex; Runnable runnable = new BatchInsertRunnable(list,startIndex, endIndex); executorService.execute(runnable); } executorService.shutdown(); while(!executorService.isTerminated()){ //wait for all thread to finish }
相关问题

请帮我实现使用多线程进行数据库插入大量数据的java代码

好的,以下是使用多线程进行数据库插入大量数据的Java代码示例: ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class InsertDataMultiThread { private static final String DB_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydatabase"; private static final String DB_USER = "root"; private static final String DB_PASSWORD = "password"; private static final int THREAD_POOL_SIZE = 10; private static final int BATCH_SIZE = 1000; public static void main(String[] args) { Connection dbConnection = null; try { // 获取数据库连接 dbConnection = getDBConnection(); // 设置自动提交为 false dbConnection.setAutoCommit(false); // 创建一个线程池 ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); // 创建一个 PreparedStatement 对象 PreparedStatement preparedStatement = dbConnection.prepareStatement("INSERT INTO mytable (col1, col2, col3) VALUES (?, ?, ?)"); // 构造数据列表 List<Data> dataList = new ArrayList<>(); for (int i = 0; i < 1000000; i++) { Data data = new Data("value1", "value2", "value3"); dataList.add(data); } // 将数据列表分割成多个批次 List<List<Data>> batches = splitIntoBatches(dataList, BATCH_SIZE); // 依次将每个批次提交到线程池中执行 for (List<Data> batch : batches) { Runnable task = new InsertDataTask(preparedStatement, batch); executor.execute(task); } // 关闭线程池 executor.shutdown(); // 等待所有任务执行完毕 while (!executor.isTerminated()) {} // 提交事务 dbConnection.commit(); System.out.println("Data inserted successfully."); } catch (SQLException e) { System.err.println(e.getMessage()); } finally { try { if (dbConnection != null) { // 恢复自动提交 dbConnection.setAutoCommit(true); // 关闭数据库连接 dbConnection.close(); } } catch (SQLException e) { System.err.println(e.getMessage()); } } } private static Connection getDBConnection() throws SQLException { Connection dbConnection = null; try { Class.forName(DB_DRIVER); } catch (ClassNotFoundException e) { System.err.println(e.getMessage()); } dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); return dbConnection; } private static <T> List<List<T>> splitIntoBatches(List<T> list, int batchSize) { List<List<T>> batches = new ArrayList<>(); int size = list.size(); for (int i = 0; i < size; i += batchSize) { batches.add(list.subList(i, Math.min(size, i + batchSize))); } return batches; } private static class InsertDataTask implements Runnable { private PreparedStatement preparedStatement; private List<Data> dataList; public InsertDataTask(PreparedStatement preparedStatement, List<Data> dataList) { this.preparedStatement = preparedStatement; this.dataList = dataList; } @Override public void run() { try { for (Data data : dataList) { preparedStatement.setString(1, data.getCol1()); preparedStatement.setString(2, data.getCol2()); preparedStatement.setString(3, data.getCol3()); preparedStatement.addBatch(); } preparedStatement.executeBatch(); } catch (SQLException e) { System.err.println(e.getMessage()); } } } private static class Data { private String col1; private String col2; private String col3; public Data(String col1, String col2, String col3) { this.col1 = col1; this.col2 = col2; this.col3 = col3; } public String getCol1() { return col1; } public void setCol1(String col1) { this.col1 = col1; } public String getCol2() { return col2; } public void setCol2(String col2) { this.col2 = col2; } public String getCol3() { return col3; } public void setCol3(String col3) { this.col3 = col3; } } } ``` 在这个示例代码中,我们使用了线程池来并发执行大量的数据库插入操作。每个线程负责将一个批次的数据插入到数据库中。我们将数据列表分割成多个批次,每个批次的大小为 BATCH_SIZE,然后依次将每个批次提交到线程池中执行。在每个线程中,我们使用 PreparedStatement 对象来执行批量插入操作,可以有效地减少数据库连接和交互的次数。当所有任务执行完毕后,我们提交事务并关闭数据库连接。 如果你想要使用这个示例代码,需要将 DB_CONNECTION、DB_USER 和 DB_PASSWORD 替换成你自己的数据库连接信息,同时需要创建一个名为 mytable 的表,并且包含三个文本列 col1、col2 和 col3。

java实现使用线程池多线程分页插入数据

好的,下面是使用线程池多线程分页插入数据的 Java 代码示例: 首先,我们需要定义一个线程池,并设置最大线程数为 10: ``` ExecutorService executorService = Executors.newFixedThreadPool(10); ``` 接下来,我们需要获取总记录数,以及每页的记录数和总页数: ``` int totalNum = getTotalNum(); // 获取总记录数 int pageSize = 100; // 每页的记录数 int pageNum = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1; // 总页数 ``` 然后,我们可以使用循环来遍历每一页,并提交任务给线程池: ``` for (int i = 1; i <= pageNum; i++) { final int currentPage = i; executorService.submit(new Runnable() { @Override public void run() { List<Data> dataList = getDataList(currentPage, pageSize); // 获取当前页的数据列表 insertDataList(dataList); // 插入数据 } }); } ``` 在任务的 run 方法中,我们首先需要获取当前页的数据列表,然后调用插入数据的方法来插入数据: ``` public List<Data> getDataList(int currentPage, int pageSize) { // 根据当前页和每页的记录数查询数据 // ... } public void insertDataList(List<Data> dataList) { // 插入数据 // ... } ``` 最后,我们需要关闭线程池: ``` executorService.shutdown(); ``` 完整的代码示例: ``` ExecutorService executorService = Executors.newFixedThreadPool(10); int totalNum = getTotalNum(); // 获取总记录数 int pageSize = 100; // 每页的记录数 int pageNum = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1; // 总页数 for (int i = 1; i <= pageNum; i++) { final int currentPage = i; executorService.submit(new Runnable() { @Override public void run() { List<Data> dataList = getDataList(currentPage, pageSize); // 获取当前页的数据列表 insertDataList(dataList); // 插入数据 } }); } executorService.shutdown(); ``` 需要注意的是,该示例仅是一个简单的示例,实际使用中还需要考虑一些细节问题,比如异常处理、分页查询的 SQL 语句等。

相关推荐

最新推荐

recommend-type

java实现把一个List集合拆分成多个的操作

主要介绍了java实现把一个List集合拆分成多个的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

JAVA JDK8 List分组获取第一个元素的方法

今天小编就为大家分享一篇关于JAVA JDK8 List分组获取第一个元素的方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
recommend-type

mybatis 批量将list数据插入到数据库的实现

主要介绍了mybatis 批量将list数据插入到数据库的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

详解Python多线程下的list

主要介绍了Python多线程下的list的相关资料,文中示例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
recommend-type

java比较两个list是否相同equals的代码详解

在本篇文章里小编给大家分享的是关于java比较两个list是否相同equals的代码详解,有需要的朋友们可以参考学习下。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。