我正在使用 ThreadPoolExecutor 在我的 Java 应用程序中实现线程。
我有一个 XML,我需要解析它并将其每个节点添加到线程中以执行完成。我的实现是这样的:
parse_ip 是创建的线程池对象,ParseQuotes XML 是具有 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 Executor 中实现相同的效果。还想问一下finally块中写的代码是否正确关闭线程池?
谢谢,
阿米特
A CountDownLatch http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html正是为此目的而设计的。可以找到例子here https://stackoverflow.com/a/11372932/230513 and here http://groups.google.com/group/comp.lang.java.programmer/msg/1d9c821dcda040f6。当事先不知道线程数时,可以考虑Phaser https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html,Java 1.7 中的新功能,或者UpDownLatch http://groups.google.com/group/comp.lang.java.programmer/browse_frm/thread/2342bd25ac3dd6b9.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)