mysql 多线程 事务_jdbc批处理+手动事务+多线程实现81秒插入千万数据(多线程版)...

本文通过Java JDBC批处理配合多线程技术,展示了如何在81秒内完成千万数据的插入。代码示例中创建了一个固定大小的线程池,每个线程执行批量插入操作,最后通过CountDownLatch同步所有线程。实验结果显示多线程比单线程速度显著提升,但需要注意防止内存溢出,需适当调整线程数量和JVM参数。
摘要由CSDN通过智能技术生成

现在来试试多线程能够多少秒钟插入千万数据

/**

* @Author: guandezhi

* @Date: 2019/4/13 15:35

*/

public class JdbcUtils {

private static String url = "jdbc:mysql://localhost:3306/user?useSSL=false&rewriteBatchedStatements=true";

private static String user = "root";

private static String password = "root";

private static ExecutorService threadPool = Executors.newFixedThreadPool(50);

public static void executeBatch() {

Connection conn = null;

PreparedStatement ps = null;

try {

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection(url, user, password);

String sql = "insert into user(name, mobile) values(?,?)";

conn.setAutoCommit(false);

ps = conn.prepareStatement(sql);

for (int j = 0; j < 100000; j++) {

String mobile = "13356544556";

Integer randNum = 0;

Random random = new Random();

for (int i = 0; i < 1000; i++) {

randNum = random.nextInt(10);

}

ps.setString(1, "官德志");

ps.setString(2, mobile + String.valueOf(randNum));

ps.addBatch();

}

ps.executeBatch();

conn.commit();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

public static void main(String[] args) throws InterruptedException {

long beginTime = System.currentTimeMillis();

CountDownLatch latch = new CountDownLatch(100);

for (int i = 0; i < 100; i++) {

threadPool.execute(() -> {

try {

JdbcUtils.executeBatch();

} catch (Exception e) {

System.out.println("插入数据异常");

} finally {

latch.countDown();

}

});

}

latch.await();

long endTime = System.currentTimeMillis();

System.out.println("插入一千万数据用时:" + (endTime - beginTime) / 1000 + " 秒");

threadPool.shutdown();

}

}

测试一下

总结:

1.多线程确实比单线程快很多

2.此处开启多线程容易造成OOM,需要合理的设置线程大小和JVM参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值