如何检查Java中的While条件下是否有任何线程(CompletableFuture)未完成?
我正在设置一个网络爬虫,希望支持多线程处理。种子URL可能返回多个URL。为保持生成线程(CompletableFuture)以爬网URL设置了一个循环 我遇到了设置While条件的问题。如何检查所有CompletableFuture是否已完成(或其中任何一项尚未完成)? 在我看来,有两种方法可能有效:如何检查Java中的While条件下是否有任何线程(CompletableFuture)未完成?,java,multithreading,concurrency,parallel-processing,completable-future,Java,Multithreading,Concurrency,Parallel Processing,Completable Future,我正在设置一个网络爬虫,希望支持多线程处理。种子URL可能返回多个URL。为保持生成线程(CompletableFuture)以爬网URL设置了一个循环 我遇到了设置While条件的问题。如何检查所有CompletableFuture是否已完成(或其中任何一项尚未完成)? 在我看来,有两种方法可能有效: 创建一个AtomicInteger,并使用递增和递减来记录创建和完成的可完成未来。在每个循环中检查它 创建一个列表来存储每个CompletableFuture,并检查是否在每个循环中都完成了所有
//queue for storing urls
this.unvisitedURLsAndPaths = new ConcurrentLinkedDeque<>();
//Loop If we can poll a url with path from the queue Or any crawler has not finished its job
while ((urlAndPath=this.unvisitedURLsAndPaths.pollLast())!=null/*OR ANY CRAWLER HAS NOT FINISHED ITS JOB*/) {
// If we have the url with path
if (urlAndPath!=null){
//remember the url and path for filtering by crawlers
this.visitedURLsAndPaths.put(urlAndPath[0],urlAndPath[1]);
//give the url and path to the crawler
Crawler crawler = new Crawler(urlAndPath[0], urlAndPath[1], this);
//crawlers do the job(get new urls with paths and filter them) and they would offer the result(a collection of unvisited urls with paths) to the queue
CompletableFuture.supplyAsync(()->crawler.work());
}
}
//用于存储URL的队列
this.unvisitedURLsAndPaths=新的ConcurrentLinkedQue();
//如果我们可以使用队列中的路径轮询url,或者任何爬虫程序尚未完成其工作,则循环
而((urlAndPath=this.unvisitedurlsandpath.pollLast())!=null/*或任何爬虫程序尚未完成其作业*/){
//如果我们有带路径的url
if(urlAndPath!=null){
//记住爬虫过滤的url和路径
this.visitedUrlsandPath.put(urlAndPath[0],urlAndPath[1]);
//提供爬虫程序的url和路径
爬虫爬虫器=新爬虫器(urlAndPath[0],urlAndPath[1],此);
//爬虫完成这项工作(获取带有路径的新URL并对其进行过滤),它们将向队列提供结果(带有路径的未访问URL的集合)
CompletableFuture.supplyAsync(()->crawler.work());
}
}
此方法没有错误创建一个列表来存储每个可完成的未来,并检查每个循环中是否完成了所有操作
此方法没有错误创建一个列表来存储每个可完成的未来,并检查每个循环中是否完成了所有操作