【发布时间】:2016-08-21 18:12:09
【问题描述】:
我正在尝试使用多线程方法运行几个查询,但是我认为我做错了什么,因为我的程序需要大约五分钟来运行一个简单的 select 语句,例如
SELECT * FROM TABLE WHERE ID = 123'
我的实现如下,我正在使用一个连接对象。
在我的运行方法中
public void run() {
runQuery(conn, query);
}
runQuery 方法
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 方法中,我使用下面的 sn-p 启动线程。
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);
【问题讨论】:
-
您能否添加更多信息:您使用的是什么数据库?你是如何构建连接的?没有所有线程的东西,只有一个查询需要多长时间?
-
我使用的是 SQL Server 2008。没有线程的东西,代码在几毫秒内执行。实际上不到一秒钟。
标签: java sql database multithreading jdbc