我看到一个stackoverflow成员建议使用Thread.join()让一个“主”线程等待两个“任务”线程完成。
我会经常做一些不同的事情(如下所示),我想知道我的方法是否有任何问题。
final CountDownLatch latch = new CountDownLatch(myItems.length);
for (Item item : myItems) {
//doStuff launches a Thread that calls latch.countDown() as it's final act
item.doStuff(latch);
}
latch.await(); //ignoring Exceptions for readability发布于 2010-09-29 22:34:58
您的解决方案更易于扩展。在创建CountdownLatch和其他同步器之前,Thread.join()是解决问题的一种非常好的方法。
在可读性方面,我会选择CountdownLatch方法,而不是在每个线程上连接。这还允许您更改Item的实现,以可能提交给Executor服务,而不是直接使用Thread。
发布于 2010-09-29 22:44:32
我更喜欢使用Future (如果你使用的是ExecutorService,这很简单)。然后,在提交所有任务后,等待它们全部完成。
Collection<Future<Void>> futures = new ArrayList<Future<Void>>(myItems.length());
for ( Runnable item : myItems ) {
futures.add(executor.submit(item, null));
for ( Future<Void> future : futures )
future.get(); //easy to add a timeout here最后的for循环可以很容易地分成一个实用的方法。这封装了同步,并使添加超时变得容易。
它也更适用于一般情况,即工作线程实际上需要返回一个结果。(如果您不关心工作线程最终做了什么,为什么还要等待它们呢?)
发布于 2010-09-29 22:43:13
对于同时启动所有线程,优选的是倒计时锁存器。
https://stackoverflow.com/questions/3822608
复制相似问题