CountDownLatch的latch.await()方法与Thread.join() [英] A CountDownLatch's latch.await() method vs Thread.join()

查看:197
本文介绍了CountDownLatch的latch.await()方法与Thread.join()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一个stackoverflow成员建议使用Thread.join()让主"线程等待2个任务"线程完成.

I saw a stackoverflow member suggest using Thread.join() to have a "main" thread wait for 2 "task" threads to complete.

我经常会做一些不同的事情(如下所示),我想知道我的方法是否有问题.

I will frequently do something different (shown below) and I want to know if there are any problems with my approach.

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

推荐答案

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

Your solution is easier to scale. Thread.join() was a perfectly fine way of resolving your issue before CountdownLatch and the other synchronizers were created.

就可读性而言,我将选择CountdownLatch方法,而不是在每个线程上进行连接.这也使您可以更改Item的实现,以使其可以提交给Executor服务,而不是直接使用Threads.

In terms of readability, I would choose the CountdownLatch approach over joining on each thread. This also allows you to change the implementation of Item to maybe submit to an Executor service instead of using Threads directly.

这篇关于CountDownLatch的latch.await()方法与Thread.join()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆