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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With