views:

218

answers:

2

I'm looking for the simplest, most straightforward way to implement the following:

  • main starts and launches 3 threads
  • all 3 tasks process and end in a resulting value (which I need to return somehow?)
  • main waits (.join?) on each thread to ensure they have all 3 completed their task
  • main somehow gets the value from each thread (3 values)

Then the rest is fairly simple, processes the 3 results and then terminates...

Now, I've been doing some reading and found multiple ideas, like:

  • Using Future, but this is for asynch, is this really a good idea when the main thread needs to block waiting for all 3 spawned threads to finsih?
  • Passing in an object (to a thread) and then simply having the thread "fill it" with the result
  • Somehow using Runnable (not sure how yet).

Anyways - what would be the best, and simplest recommended approach? Thanks,

+7  A: 
List<Callable<Result>> list = ... create list of callables

ExecutorService es = Executors.newFixedThreadPool(3);
List<Future<Result>> results = es.invokeAll(list);

ExecutorService.invokeAll method will return only after all tasks (instances of Callable) finished, either normally or by throwing exception.

For details see ExecutorService (mainly its invokeAll method), Executors, Callable.

Peter Štibraný
I suggest using a newCachedThreadPool or newFixedThreadPool(list.size()) in case the number of tasks changes. Someone could change the number of tasks without realising the importance of the number 3 and it would all work of course, but not be as efficient as intended.
Peter Lawrey
Yes, I completely agree to that. At first I also used newCachedThreadPool() in my example, but later changed it to use fixed thread pool with 3 threads, as that was what Shaitan00 asked for.
Peter Štibraný
A: 

You could also use a Semaphore from java.util.concurrent.

Create a new Semaphore with 1 - #threads permits and have main call acquire() on the Semaphore.

When each of the threads you have created has finished it's work, get it to call the release() method.

As you have created a Semaphore with a negative number of permits the call to acquire() will block until this number becomes positive. This will not happen until all of your threads have released a permit on the Semaphore.

slappybag