开发者

Collecting Return Values from Launched Threads? [latest Java]

开发者 https://www.devze.com 2022-12-13 09:37 出处:网络
I\'m looking for the simplest, most straightforward way to implement the following: main starts and launches 3 threads

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 i开发者_高级运维dea 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,


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消