我想在Java中并行执行我的soap请求调用。 我是多线程新手,没有办法做到这一点。
public List<TB600Model.Response> getTableDesc(final List<TB600Model.Request> requests)
{
List<TB600Model.Response> responses = new ArrayList<>();
for (TB600Model.Request request : requests)
{
responses.add(
this.modifyDescription(
this.getDescription(
request.getSite()
,request.getDescType()
,request.getKeyData()
,request.getEffMdy()
)
,request.getDescType()
,request.getKeyData()
)
);
}
return responses;
}
答案 0 :(得分:1)
对于Java 8+,请尝试改用此方法:
requests.parallelStream().forEach(request -> {...});
输入 response.add 而不是...
对于早期版本:
ExecutorService es = Executors.newFixedThreadPool(10);
List<Response> responses = new ArrayList<>();
for(Request request: requests){
Future<Response> future = es.submit(new Callable<Response>() {
@Override
public Response call() throws Exception {
//create your response here and return
}
});
try {
responses.add(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}