Question

I would like to perform the following algorithm - this must 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 desirable that threads are not continuously created and destroyed due to overheads (and the fact that each thread will have <20milli seconds of work), which brought about the idea of Thread Pools1. I also know that using Executable2, one can call shutdown, and then awaitTermination. However it is not desirable in this case due to the loop. Thus how can thread synchronization occur?

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

Was it helpful?

Solution

Have you tried looking at a Cyclic Barrier. It is optimized to allow a group of threads to stop and wait till everyone has reached a common barrier. I can't seen any reason why it can't be used with known number of pooled threads with references to a common barrier. There could be some additional complexity if you need to synchronize on the callback invoked with the barriers await() count is reached because it executes in a different thread.

OTHER TIPS

You need to stick all your tasks in a queue, then feed the queue to a ThreadPoolExecutor. You tell the thread pool executor how many threads to use and it takes care of executing the tasks.

Have a look at the fork/ join framework of jdk 7.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top