我有一个请求对象的数组列表。我在 for 循环中运行它们,在循环内我调用 web 服务并将响应对象添加到另一个数组列表中。我需要实现线程,以便可以向 Web 服务发送多个请求。
问问题
675 次
1 回答
0
我自己并没有真正尝试过,但认为它可能很有趣,所以我玩弄了它,希望它能满足你的要求:
List<RefundOrderResponse> responses = Collections.synchronizedList(new ArrayList<RefundOrderResponse>());
Executor e = Executors.newFixedThreadPool(10);
CompletionService<RefundOrderResponse> ecs = new ExecutorCompletionService<RefundOrderResponse>(e);
// Create some futures based on the requests we have that we want processed
List<Future<RefundOrderResponse>> futures = new ArrayList<Future<RefundOrderResponse>>();
for (final RefundOrderRequest request : requests)
{
futures.add(ecs.submit(new Callable<RefundOrderResponse>()
{
@Override
public RefundOrderResponse call () throws Exception
{
// do the call to the web service here and return the response
return soapWS.refundOrder(request);
}
}));
}
// Now we can process the response, note with a completion service we are assuming process order of responses is not very important.
for (int i = 0; i < futures.size(); i++) {
responses.add(ecs.take().get());
}
我在这里使用了 Java CompletionService,或者更具体地说是ExecutorCompletionService(因为它使用 executor 并行运行)。它确实假设响应的处理可以按任何顺序完成,在这种情况下只是将它们添加到响应列表中。不确定您打算对响应列表做什么,但是您可以在循环中处理它们而不是将它们添加到列表中。
于 2012-09-18T11:24:57.897 回答