java 多线程Executors开启多事务,插入数据

package com.movie.api.utils.ddl;
import com.movie.api.utils.DataTimeUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class InsertData {
    private static final String URL = "jdbc:mysql://localhost:3306/movie?characterEncoding=utf8&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "pyrx123";
    private static final int THREAD_COUNT = 30;
    private static final int ITERATIONS_PER_THREAD = 100000;

    public static void main(String[] args) throws SQLException, InterruptedException {
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        conn.setAutoCommit(false); // 开启事务
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);

        for (int i = 0; i < THREAD_COUNT; i++) {
            executor.execute(() -> {
                try {
                    for (int j = 0; j < ITERATIONS_PER_THREAD; j++) {
                        String sql = "INSERT INTO `t_order` (`id`, `uid`, `phone`, `aid`, `seats`, `price`, `status`, `create_at`, `pay_at`) VALUES (?, ?, ?,?, ?, ?,?, ?, ?)";
                        PreparedStatement statement = conn.prepareStatement(sql);
                        statement.setString(1, UUID.randomUUID().toString());
                        statement.setString(2, UUID.randomUUID().toString());
                        statement.setString(3, "1551030"+j);
                        statement.setString(4, UUID.randomUUID().toString());
                        statement.setString(5, "19号18号");
                        statement.setString(6, j+".00");
                        statement.setString(7, "2");
                        statement.setString(8, DataTimeUtil.getNowTimeString());
                        statement.setString(9, DataTimeUtil.getNowTimeString());
                        statement.addBatch();
                        statement.executeBatch();
                        System.out.println("currentTimeMillis-----------------"+System.currentTimeMillis());
                        conn.commit();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executor.shutdown(); // 关闭线程池
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值