Collecting return values ​​from running threads? [latest version of java]

I am looking for the simplest, easiest way to implement the following:

  • main starts and starts 3 threads
  • all 3 tasks are processed and end with the resulting value (which do I need to return somehow?)
  • main waits (.join?) in each thread to make sure that all 3 have completed their task.
  • main somehow gets a value from each thread (3 values)

Then the rest is pretty simple, processes 3 results, and then completes ...

Now I'm reading and found some ideas, for example:

  • Using Future, but this is for asynch, is it really a good idea when the main thread should block the wait for all 3 spawned threads for finsih?
  • Passing an object (to a stream) and then just having the stream "fill it" with the result
  • Somehow use Runnable (don't know how to do it yet).

In any case, what would be the best and simplest recommended approach? Thanks,

+3
source share
2 answers
List<Callable<Result>> list = ... create list of callables

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

ExecutorService.invokeAll the method will return only after completion of all tasks (Callable instances), as usual, or by throwing an exception.

For more details see ExecutorService(mainly him invokeAll) Executors,, Callable.

+8
source

You can also use Semaphore from java.util.concurrent.

Create a new Semaphore with permission 1 - #threads and get the main call () on the Semaphore.

, release().

, () , . , .

0

Source: https://habr.com/ru/post/1724706/


All Articles