I have the following situation:
In order to run a algorithm, i must run several threads and each thread will set a instance variable x, right before it dies. The problem is that these threads dont return immediately:
public Foo myAlgorithm()
{
//create n Runnables (n is big)
//start these runnables (may take long time do die)
//i need the x value of each runnable here, but they havent finished yet!
//get average x from all the runnables
return new Foo(averageX);
}
Should i use wait notify ? Or should i just embed a while loop and check for termination ?
Thanks everyone!
Create some shared storage to hold the
xvalue from each thread, or just store the sum if that’s sufficient. Use aCountDownLatchto wait for the threads to terminate. Each thread, when finished, would callCountDownLatch.countDown()and yourmyAlgorithmmethod would use theCountDownLatch.await()method to wait for them.Edit: Here’s a complete example of the approach I suggested. It created 39 worker threads, each of which adds a random number to a shared sum. When all of the workers are finished, the average is computed and printed.
The output should be something like this:
Edit: Just for fun, here is an example using
ExecutorService,Callable, andFuture.The output should look like this: