I want to have 3 threads running in parallel and return the results in parallel, so that when a task returns true when it has generated the right number, all the other threads stop executing.
I have tried using a CallableFuture and Callable with a newFixedThreadPool, but I seem to get the desired result. The problem each time is that I have to wait for all the results to be completed, yet I simply want to stop all threads if one thread has found the random number I am looking for.
Here is the following pseudocode:
public class GenerateRandomIntegerTask implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
// From constructor
int rand1 = rand1;
int rand2 = rand2;
// Do the work here
Rand rand = new Random();
int rand3 = random.nextInt(100);
if(rand1 + rand2 + rand3 == 5)
{
// STOP ALL TRHREADS
return true;
}
else
{
return false;
}
}
}
I execute this using a newFixedThreadPool like so:
MultiValuedMap<Integer, Integer> randMap = randHelper.retrieveRandMap();
Iterator it = randMap.entries().iterator();
ExecutorService executor = Executors.newFixedThreadPool(3);
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
int rand1 = pair.getKey().toString();
String rand2 = pair.getValue().toString();
executor.submit(new GenerateRandomIntegerTask (rand1, rand2));
}
Does anybody know how to achieve this?
And before you mark it as duplicate, please take some time to consider whether it really is because I haven't seen other questions describing this exact same problem.