Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is how ExecutorService and ExecutorCompletionService can solve it:</p> <pre><code>public class MaxFinder { private int[] values; private int threadsCount; public MaxFinder(int[] values, int threadsCount) { this.values = values; this.threadsCount = threadsCount; } public int find() throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(threadsCount); ExecutorCompletionService&lt;Integer&gt; cs = new ExecutorCompletionService&lt;Integer&gt;(executor); // Split the work int perThread = values.length / threadsCount; int from = 0; for(int i = 0; i &lt; threadsCount - 1; i++) { cs.submit(new Worker(from, from + perThread)); from += perThread; } cs.submit(new Worker(from,values.length)); // Start collecting results as they arrive int globalMax = values[0]; try { for(int i = 0; i &lt; threadsCount; i++){ int v = cs.take().get(); if (v &gt; globalMax) globalMax = v; } } catch (ExecutionException e) { throw new RuntimeException(e); } executor.shutdown(); return globalMax; } private class Worker implements Callable&lt;Integer&gt; { private int fromIndex; private int toIndex; public Worker(int fromIndex, int toIndex) { this.fromIndex = fromIndex; this.toIndex = toIndex; } @Override public Integer call() { int max = values[0]; for(int i = fromIndex; i&lt;toIndex; i++){ if (values[i] &gt; max) max = values[i]; } return max; } } } </code></pre> <p>In this solution, N threads work concurrently, each on its portion of the array. The caller thread is responsible for gathering the local maximums as they arrive, and find the global maximum. This solution uses some non-trivial concurrency tools from java.util.concurrent package.</p> <p>If you prefer a solution that only uses primitive synchronization tools, then you should use a synchronized block in the worker threads, that sets the maximum in some data member and then notifies the collector thread. The collector thread should be in a loop, waiting for notification and then examining the new number, and updating the global maximum if needed. This "consumer producer" model requires careful synchronization.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload