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.
await()
?join()
? We can store all the instance of the threads and check for status and wait. Is that a good way to do this.You should use an ExecutorService
. You can obtain one using n threads by calling:
ExecutorService executor = Executors.newFixedThreadPool( n );
Then, you can start a task as follow:
executor.submit( runnable );
At the end, you can stop executor by calling shutdown()
method. Doing that, no task can be added anymore but all submitted tasks will be executed. You can also wait for shutdown:
executor.shutdown();
while ( !executor.isTerminated() ) {
try {
executor.awaitTermination( 5, TimeUnit.SECONDS);
} catch ( InterruptedException e ) {
}
}