gpt4 book ai didi

java - JDBC 和多线程

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:14 25 4
gpt4 key购买 nike

我正在尝试使用多线程方法运行一些查询,但是我认为我做错了什么,因为我的程序大约需要五分钟来运行一个简单的选择语句,如

SELECT * FROM TABLE WHERE ID = 123'

我的实现如下,我使用的是一个连接对象。

在我的运行方法中

public void run() {
runQuery(conn, query);
}

运行查询方法

public void runQuery(Connection conn, String queryString){
Statement statement;
try {
statement = conn.createStatement();
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {}
} catch (SQLException e) {
e.printStackTrace();
}
}

最后,在 main 方法中,我使用下面的代码片段启动线程。

MyThread bmthread = new MyThread(conn, query);
ArrayList<Thread> allThreads = new ArrayList<>();
double start = System.currentTimeMillis();
int numberOfThreads = 1;
for(int i=0; i<=numberOfThreads; i++){
Thread th = new Thread(bmthread);
th.setName("Thread "+i);
System.out.println("Starting Worker "+th.getName());
th.start();
allThreads.add(th);
}

for(Thread t : allThreads){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
double end = System.currentTimeMillis();
double total = end - start;
System.out.println("Time taken to run threads "+ total);

更新:我现在为每个线程使用单独的连接。

ArrayList<Connection> sqlConn = new ArrayList<>();
for(int i =0; i<10; i++){
sqlConn.add(_ut.initiateConnection(windowsAuthURL, driver));
}
loop:
MyThread bmthread = new MyThread(sqlConn.get(i), query);

最佳答案

正如rohivats和Asaph所说,一个连接只能被一个线程使用,也就是说,考虑使用数据库连接池。考虑到 c3p0、DBCP 和类似的东西几乎被废弃了,我会使用 HikariCP这是非常快速和可靠的。

如果您想要非常简单的东西,您可以使用线程安全集合(例如 LinkedList)实现一个非常简单的连接池,例如:

 public class CutrePool{
String connString;
String user;
String pwd;

static final int INITIAL_CAPACITY = 50;
LinkedList<Connection> pool = new LinkedList<Connection>();
public String getConnString() {
return connString;
}
public String getPwd() {
return pwd;
}

public String getUser() {
return user;
}

public CutrePool(String connString, String user, String pwd) throws SQLException {
this.connString = connString;

for (int i = 0; i < INITIAL_CAPACITY; i++) {
pool.add(DriverManager.getConnection(connString, user, pwd));
}
this.user = user;
this.pwd = pwd;
}

public synchronized Connection getConnection() throws SQLException {
if (pool.isEmpty()) {
pool.add(DriverManager.getConnection(connString, user, pwd));
}
return pool.pop();
}

public synchronized void returnConnection(Connection connection) {
pool.push(connection);
}
}

如您所见,getConnection 和 returnConnection 方法是同步的以实现线程安全。获取连接 (conn = pool.getConnection();) 并且不要忘记在使用后返回/释放连接 (pool.returnConnection(conn);)

关于java - JDBC 和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39067373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com