我正在使用ThreadPoolExecutor在我的Java应用程序中实现线程。如何使主线程等待其他线程在ThreadPoolExecutor中完成
我有一个XML,我需要解析并将它的每个节点添加到线程来执行完成。我的实现是这样的:
parse_tp是创建的线程池对象& ParseQuotesXML是带有run方法的类。
try {
List children = root.getChildren();
Iterator iter = children.iterator();
//Parsing the XML
while(iter.hasNext()) {
Element child = (Element) iter.next();
ParseQuotesXML quote = new ParseQuotesXML(child, this);
parse_tp.execute(quote);
}
System.out.println("Print it after all the threads have completed");
catch(Exception ex) {
ex.printStackTrace();
}
finally {
System.out.println("Print it in the end.");
if(!parse_tp.isShutdown()) {
if(parse_tp.getActiveCount() == 0 && parse_tp.getQueue().size() == 0) {
parse_tp.shutdown();
} else {
try {
parse_tp.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
log.info("Exception while terminating the threadpool "+ex.getMessage());
ex.printStackTrace();
}
}
}
parse_tp.shutdown();
}
的问题是,这两个打印输出语句中的其他线程退出之前被打印出来。我想让主线程等待所有其他线程完成。 在正常的线程实现中,我可以使用join()函数来完成,但没有办法在ThreadPool执行程序中实现同样的功能。还想问一下,如果finally代码写入的代码关闭了threadpool本身?
感谢, 阿米特
感谢trashgod,但我没有确切的XML节点的数量,我需要解析,所以不会能够使用CountDownLatch。但是我没有意识到Java中有这样的属性,所以非常感谢。 – Amit 2009-12-18 10:28:27
非常好。如上所述,“Future”更加灵活,但我也添加了UpDownLatch示例的链接。 – trashgod 2009-12-18 22:06:05
另请参阅此相关的[示例](http://stackoverflow.com/a/11372932/230513)。 – trashgod 2012-09-27 03:47:13