I have a question based on the ExecutorService Thread flow regulation: I would like to .submit() multiple threads for executon where I would like some threads to wait until specific previous Threads have finished executing. .
So far I know of one such method of doing this by using CountDownLatch(). Following example illustrates 2 threads that need to finish before the third can start:
public class Example{
public static void main(String[] args) throws InterruptedException {
CountDownLatch cdl = new CountDownLatch(2); //count of 2
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(new Runnable() {
public void run() {
method1(); //simulation of a useful method 1
cdl.countDown(); //reduces the count by one
}
});
executor.submit(new Runnable() {
public void run() {
method2(); //simulation of a useful method 2
cdl.countDown();
}
});
cdl.await(); //will wait until both methods are complete
executor.submit(new Runnable() {
public void run() {
result(); //simulation of a method that needs previous threads to execute }
});
}
}
Quite obvious, such method is not the optimal for such work as, for one thing, one cannot add additional threads after the .await() that do not depend on the CDL itself.
Therefore, what are the better alternatives to regulate Thread flow with ExecutorService that allow better manipulation of Thread execution compared to CDL.