Search parellel with communication between threads

Suppose I have an int array, an element, numand 4 threads. I give each thread a 1/4 array to search num. (The search method is below)

public static boolean contains(int[] array, int minIdx, int maxIdx, int num) { ...}

At my "top level" I can schedule 4 threads to search for 4 quarters of the array, but how can I ensure that ALL threads stop searching as soon as one of them finds an element (if there is no duplicate in the array in it, so the element may not appear more than once).

PS: You see, suppose that my fourth thread found an element in the first iteration, I want the top-level method to return immediately, and not wait for the other 3 guys to finish.

+4
source share
3

. , , .

: AtomicBoolean . , . :

for (int i = start; i < end && !done.get();) {
   for (int batchLimit = Math.min(i + BATCH_SIZE, end); i < batchLimit; i++) {
       // your logic
   }
}

JIT.

, . L3. , , , .

+3

, , , . AtomicBoolean - . ,

for (int i = minIdxs ; i < maxIdxs && found.get() == false; ++i){...}

CountDownLatch 4 countDown(), .

await(), , , .

0

, . , . ( )

, , .

class ControllerOfAllTheThreads{
ArrayList<TheClassesWhichDoTheSearch> list = new ArrayList<TheClassesWhichDoTheSearch>();

public void tellThemWeFoundHim(){
    for (TheClassesWhichDoTheSearch theThreads : list) {
        if(theThreads.isAlive() && !theThreads.isInterrupted())
            theThreads.interrupt();
    }
}

}

0

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


All Articles