如何确保第一次迭代由One Thread运行,第二次迭代由Another Thread运行。
在下面的代码片段中,runQuery方法执行Query并将resultSet作为输出。
我有两个这样的查询,我想在Parallel中同时运行。
for (int i = 0; i < list.size(); i++) {
String ProcessedRecord = list.get(i);
String app_name = application.get(i);
// ResultSet feedDetails = runQuery(ProcessedRecord,app_name);
try {
System.out.println("Inside try block ... ");
ResultSet feedDetails = dat.runQuery(ProcessedRecord, app_name);
rs_feedDetails.add(feedDetails);
} catch(SQLException e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
您可以在ExecutorService
,Callables
和Futures
的帮助下完成此操作。
以下是修改后的代码:
ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); //A thread pool to execute your tasks
List<Future<ResultSet>> futures = new ArrayList<>(); //List to hold futures
for (int i = 0; i < list.size(); i++) {
String ProcessedRecord = list.get(i);
String app_name = application.get(i);
// ResultSet feedDetails = runQuery(ProcessedRecord,app_name);
try {
Future<ResultSet> toAdd = pool.submit(new Callable<ResultSet>() { //submit a callable of resultset to the pool
@Override
public ResultSet call() throws Exception {
return dat.runQuery(ProcessedRecord, app_name);
}
});
futures.add(toAdd);
} catch(SQLException e) {
e.printStackTrace();
}
}
pool.shutdown(); // shut down the thread pool
for(int i = 0; i < futures.size(); i++) {
rs_feedDetails.add(futures.get(i).get()); //invoke get method of every future in your list. The get method will return you the result.
}
修改强>
正如评论中所提到的,在某些情况下,任务可以在同一个线程上串行执行 - 可以使用ExecutorService参数强制并行,例如“parallelism”或“amountThreads”