For some processing, n
threads needs to spawned and runs in parallel. The main thread, which starts the processing should exit, after all the processing is done.
Here is the code snippet:
private void spawnThreads2(int n) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(n);
final Random random = new Random(System.currentTimeMillis());
for (int i = 1; i <= n; i++) {
final int id = i;
new Thread(){
public void run() {
try {
Thread.sleep(random.nextInt(1000)); // represents processing, can throw any Exception
} catch (Exception e) {}
finally {
latch.countDown();
}
}
}.start();
}
latch.await();
System.out.println("all completed.");
}
The countdown()
is done in the finally
block, so in case any exception happens application does not hang.
- Is this design good for creating threads and waiting for them? Is there possibility application can hang and never come out, because of the
await()
? - Is there a way we can achieve same functionality using
join()
? We can store all the instance of the threads and check for status and wait. Is that a good way to do this.