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(); // 关闭线程池
}
}
java 多线程Executors开启多事务,插入数据
最新推荐文章于 2023-11-15 12:45:00 发布