You might want to check out the java.util.concurrent package. In particular, you can use CountDownLatch as in
package de.grimm.game.ui; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(5); final CountDownLatch latch = new CountDownLatch(3); for( int k = 0; k < 3; ++k ) { executor.submit(new Runnable() { public void run() {
Obviously, this method will work only if you know the number of branched threads in advance, since you need to initialize the latch with this number.
Another way is to use condition variables, for example:
boolean done = false; void functionRunInThreadA() { synchronized( commonLock ) { while( !done ) commonLock.wait(); }
You may need to add exception handling ( InteruptedException ) and some of them.
source share