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!
use a
ExecutorService
and submit each task (as aCallable
) to ityou'll get a Future for each task submitted
Create some shared storage to hold the
x
value from each thread, or just store the sum if that's sufficient. Use aCountDownLatch
to wait for the threads to terminate. Each thread, when finished, would callCountDownLatch.countDown()
and yourmyAlgorithm
method 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:
You may make yourself known to
java.util.concurrent.Future
and all the associated stuff like ThreadPools, Executors etc. Teaser: AFuture
is a thread with a return value.