我有三个查询要运行,就像“select * from table
”他们花了这么多时间。
我想使用java并发运行并行运行所有查询,我是如何实现这一点的。
答案 0 :(得分:2)
您可以将您的数据库调用包装在Callable中,如下所示:
public class SqlTask implements Callable<ResultSet> {
private String sql;
public SqlTask(final String sql) {
this.sql = sql;
}
@Override
public ResultSet call() throws Exception {
Connection connection = ...; // get connection
Statement stmt = connection.createStatement();
return stmt.executeQuery(this.sql);
}
}
然后使用ExecutorService在parralel中执行它们,例如:
final ExecutorService executor = Executors.newCachedThreadPool();
final Future<ResultSet> futureResult1 = executor.submit (new SqlTask("SELECT * FROM table1"));
final Future<ResultSet> futureResult2 = executor.submit(new SqlTask("SELECT * FROM table2"));
final Future<ResultSet> futureResult3 = executor.submit(new SqlTask("SELECT * FROM table3"));
final ResultSet result1 = futureResult1.get();
final ResultSet result2 = futureResult2.get();
final ResultSet result3 = futureResult3.get();