Using CountDownLatch
CountDownLatch latch = new CountDownLatch (totalNumberOfTasks);
ExecutorService taskExecutor = Executors.newFixedThreadPool (4);
while (...) {
taskExecutor.execute (new MyTask ());
}
try {
latch.await ();
} catch (InterruptedException E) {
// handle
}
and inside your task (enclose in try / finally)
latch.countDown ();
Or in ExecutorService you call shutdown () and then expect Termination ()
ExecutorService taskExecutor = Executors.newFixedThreadPool (4);
while (...) {
taskExecutor.execute (new MyTask ());
}
taskExecutor.shutdown ();
try {
taskExecutor.awaitTermination (Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
...
}
Also see THIS answer
source share