Shaitan00
Shaitan00

Reputation: 1341

Collecting Return Values from Launched Threads? [latest Java]

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

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:

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

Upvotes: 3

Views: 1197

Answers (2)

slappybag
slappybag

Reputation: 103

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.

Upvotes: 0

Peter Štibraný
Peter Štibraný

Reputation: 32893

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.

Upvotes: 8

Related Questions