我看到一个 stackoverflow 成员建议使用 Thread.join() 让一个“主”线程等待 2 个“任务”线程完成。
我会经常做一些不同的事情(如下所示),我想知道我的方法是否有任何问题。
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
最佳答案
您的解决方案更易于扩展。 Thread.join() 是在创建 CountdownLatch 和其他同步器之前解决问题的完美方法。
就可读性而言,我会选择 CountdownLatch 方法而不是在每个线程上加入。这还允许您更改 Item 的实现,以可能提交给 Executor 服务,而不是直接使用线程。
关于java - CountDownLatch 的 latch.await() 方法与 Thread.join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3822608/