我正在循环查看I列表,并进行查找以获取对象。我对多线程很陌生,有没有一种不用并行流来处理这个问题的方法?
private List<MyObject> lookupById(List<String> ids) {
List<MyObject> myObjs = new ArrayList<>();
for(String id : ids) {
myObjs.add(apiService.lookUp(id));
}
return myObjs;
}发布于 2020-06-10 14:06:57
我就是这么想的:
private List<MyObject> lookupById(List<String> ids) {
List<MyObject> myObjs = Collections.synchronizedList(new ArrayList<>());
CountDownLatch countDownLatch = new CountDownLatch(ids.size());
ids.forEach(e -> {
new Thread(() -> {
myObjs.add(apiService.lookUp(e));
countDownLatch.countDown();
}).start();
});
try{
countDownLatch.await();
}catch(Exception ignored){}
return myObjs;
}还有其他的方法。
https://stackoverflow.com/questions/62305234
复制相似问题