我有Executors.newfixedThreadPool()
调用提交,显然提交返回将来包装的StringBuffer
对象。我需要在响应StringBuffer中附加结果。我可以在List<Future<StringBuffer>>
中获得结果,然后再次迭代以追加StringBuffer
。但我想在单次迭代中执行此操作,如下所示但是它附加的未来对象。有什么方法可以达到这个目的吗?
ExecutorService es = Executors.newFixedThreadPool(count);
for (int i = 0; i < count; i++) {
response.append(es.submit(new Callable<StringBuffer>() {
@Override
public StringBuffer call() {
StringBuffer res = new StringBuffer();
res = processAddresses(addresses, addressLatch);
return res;
}
}));
}
try {
addressLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
es.shutdownNow();
答案 0 :(得分:0)
你可以这样做:
final StringBuffer response = new StringBuffer();
ExecutorService es = Executors.newFixedThreadPool(count);
for (int i = 0; i < count; i++) {
es.submit(new Runnable() {
@Override
public void run() {
StringBuffer res = processAddresses(addresses, addressLatch);
response.append(res);
}
});
}
es.shutdownNow();
try {
es.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException ex) {
LOG.log(Level.SEVERE, null, ex);
}
System.out.println(response);
但订单没有被保留