Suppose I have a Master that keeps a list of SlaveThread objects. On each time step, I want the Master to run the SlaveThreads in parallel, however, at the end of the time step, I want the SlaveThreads to to wait for each other to complete the current time step before advancing forward. Also, I don’t want to reinstantiate the SlaveThreads on each time step. I have 2 possible solutions, and I don’t know how to make either of them work:
1) The run() method in SlaveThread is in a while(true) loop. After the execution of a single loop in the SlaveThread, I’ll have SlaveThread notify the Master(which I don’t know how to do), and the Master does something like
try{
for (int i = 0; i < numSlaveThreads; i++) {
while (!slaveThreads[i].getCompletedThisIter()) {
wait()
}
}
System.out.println("Joined");
}
before advancing to the next time step. How would I do this? How can I have a single SlaveThread notify just the master?
2) The run() in Slave is not in while(true) loop, then I have to call start() on it on every iteration. But the thread state of the Slave at this point will be terminated. How can I call start() on it again without reinstantiating it?
That is exactly what barriers are for, you can realize this with a CyclicBarrier or a CountDownLatch. These are synchronizers used to delay the progress of threads until the desired state is reached, in your case the threads have completed their computation.
Here it depends on the details how you want to realize:
For the
CyclicBarrierthat would done in the following fashion:Then in the
Runnabledefinition of your slaves you will insert at the end of the computation:barrier.await()Your slave threads will not proceed, until all your threads have finished the computation. This way you do not need to realize signaling between another master thread.
If, however, you have some code you want to execute after all threads have reached that position (master signaling) you can pass an additional
Runnableto theCyclicBarrierconstructor, which will be executed after all threads have arrived at the barrier.