CountDownLatch的latch.await()方法与Thread.join()

Iva*_*van 7 java multithreading

我看到一个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
Run Code Online (Sandbox Code Playgroud)

Joh*_*int 8

您的解决方案更容易扩展.Thread.join()是在CountdownLatch和其他同步器创建之前解决问题的完美方式.

在可读性方面,我会选择CountdownLatch方法而不是加入每个线程.这也允许您将Item的实现更改为可以提交给Executor服务而不是直接使用Threads.


Mar*_*ers 8

我更喜欢使用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
Run Code Online (Sandbox Code Playgroud)

最终的for循环可以很容易地分成一个utily方法.这封装了同步并可以轻松添加超时.

它也更适用于一般情况,其中工作线程实际上需要返回结果.(如果你不关心工作线程最终做什么,为什么还要等待它们?)