How it works...

The following screenshot shows the result of an execution of this example:

The problem resolved in the example is simple. We have a big matrix of random integers, and you want to know the total number of occurrences of a number in this matrix. To get better performance, we used the divide and conquer technique. We divided the matrix into five subsets and used a thread to look for the number in each subset. These threads are objects of the Searcher class.

We used a CyclicBarrier object to synchronize the completion of the five threads and execute the Grouper task to process partial results and calculate the final one.

As mentioned earlier, the CyclicBarrier class has an internal counter to control how many threads need to arrive at the synchronization point. Each time a thread arrives at the synchronization point, it calls the await() method to notify the CyclicBarrier object that a thread has arrived at its synchronization point. CyclicBarrier puts the thread to sleep until all the threads reach the synchronization point.

When all the threads have arrived, the CyclicBarrier object wakes up all the threads that were waiting in the await() method. Optionally, it creates a new thread that executes a Runnable object passed as the parameter in the construction of CyclicBarrier (in our case, a Grouper object) to do additional tasks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.234.192