java 多线程批量修改数据
时间: 2023-11-24 13:51:29 浏览: 116
以下是Java多线程批量修改数据的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BatchUpdateDemo {
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
conn.setAutoCommit(false);
String sql = "update user set age = ? where id = ?";
pstmt = conn.prepareStatement(sql);
// 模拟需要修改的数据
int[] ids = {1, 2, 3, 4, 5};
int[] ages = {20,21, 22, 23, 24};
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 批量修改数据
for (int i = 0; i < ids.length; i++) {
int id = ids[i];
int age = ages[i];
executorService.execute(() -> {
try {
pstmt.setInt(1, age);
pstmt.setInt(2, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
// 关闭线程池
executorService.shutdown();
while (!executorService.isTerminated()) {
Thread.sleep(100);
}
// 提交事务
conn.commit();
} catch (ClassNotFoundException | SQLException | InterruptedException e) {
e.printStackTrace();
try {
if (conn != null) {
conn.rollback();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
该示例代码使用了线程池来批量修改数据,通过创建一个固定大小的线程池,将每个修改操作封装成一个任务,交给线程池去执行。这样可以避免频繁地创建和销毁线程,提高了程序的性能。
阅读全文
相关推荐
















