Java thread pool synchronization

I would like to execute the following algorithm - this should be done in Java

for(int i = 0; i< 100; i++){ create 8 threads which perform a task wait for all threads to finish } 

It is advisable that threads are not continuously created and destroyed due to overhead (and the fact that each thread will have <20 milliseconds of operation), which triggered the idea of ​​thread pools 1 . I also know that using Executable 2 , you can call shutdown and then wait for Termination. However, in this case, this is undesirable due to the cycle. So how is thread synchronization going?

I would like to synchronize the threads in the thread pool, as would be done using the traditional join join () method.

+4
source share
3 answers

You tried to look at the cyclic barrier . It is optimized to allow a group of threads to stop and wait until everyone has reached a common barrier. I see no reason why it cannot be used with a known number of combined threads with links to a common barrier. There may be some additional complexity if you need to synchronize the callback caused by await() barriers, because it is being executed in a different thread.

+4
source

You need to insert all your tasks into the queue, and then submit the queue to ThreadPoolExecutor . You tell thread executors the thread how many threads to use, and it takes care of the tasks.

+2
source

Take a look at the fork / join structure for jdk 7.

0
source

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


All Articles