public List<ApodItem> decorateRssItemsWithLinkImages(List<RssItem> rssItems) {
ArrayList<ApodItem> apodItems = new ArrayList<>(rssItems.size());
final CountDownLatch fetchLinkLatch = new CountDownLatch(rssItems.size());
for (RssItem rssItem : rssItems) {
final ApodItem apodItem = new ApodItem();
apodItem.rssItem = rssItem;
fetchLinkPage(rssItem.link, new PageScrapedCallback() {
@Override
public void onPageScraped(@Nullable List<String> imageUrls) {
apodItem.largeImageUrl = imageUrls != null && !imageUrls.isEmpty()
? imageUrls.get(0)
: null;
fetchLinkLatch.countDown();
}
});
apodItems.add(apodItem);
}
// Wait for all link fetches to complete, despite running them in parallel...
Util.awaitUninterruptibly(fetchLinkLatch);
return apodItems;
}
在一个死循环中去检查计数器是否countDonw到了0,如果到了0,表示所有并发任务全部完成,那么死循环退出。
public static void awaitUninterruptibly(CountDownLatch latch) {
while (true) {
try {
latch.await();
return;
} catch (InterruptedException e) {
// Keep going...
}
}
}
试着想一想,是否还有其他方式控制并发?
AtomInteger??