Take a look at this example and see if it helps you:
package callrandom;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import static java.lang.System.exit;
import static java.lang.System.out;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Logger.getLogger;
import static callrandom.Randomize.gotFive;
public class CallRandom {
public static void main(String[] args){
int MAXTHREADS = 5;
List<Future<Integer>> futs = new ArrayList<>();
ExecutorService executor = newFixedThreadPool(MAXTHREADS);
ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
for (int x = 0; x < MAXTHREADS; x++) {
out.println("Run instance: " + x);
futs.add(executor.submit(new Randomize()));
}
do {
} while (!gotFive);
for (int x = 0; x < MAXTHREADS; x++) {
if (futs.get(x).isDone()) {
try {
out.println("Return from thread: " + x + " = " + futs.get(x).get());
} catch (InterruptedException | ExecutionException ex) {
getLogger(CallRandom.class.getName()).log(SEVERE, null, ex);
throw new RuntimeException(ex);
}
}
out.println("Cancel instance: " + x + " = " + futs.get(x).cancel(true));
}
exit(0);
}
}
...and the thread:
package callrandom;
import static java.lang.System.in;
import static java.lang.System.out;
import static java.lang.Thread.currentThread;
import java.util.Scanner;
import java.util.concurrent.Callable;
public class Randomize implements Callable<Integer> {
public static volatile Boolean gotFive = false;
@Override
public Integer call() throws Exception {
return findNumber();
}
private Integer findNumber() throws InterruptedException {
int number = 0;
do {
Scanner sc = new Scanner(in);
out.println(currentThread().getName() + ": Insert a number [5 stops this threads and triggers main thread to interrupt all others]:");
number = sc.nextInt();
} while (number != 5 && !gotFive);
gotNumber();
return number;
}
public synchronized void gotNumber() {
out.println(currentThread().getName() + " got a 5!");
gotFive = true;
}
}
You have 5 threads running and waiting for input. They keep asking for input until you enter the number 5 in any one of them. That thread returns to main thread and the main thread cancels all remaining threads. You may have to complete a cycle, meaning inserting at least 1 number in each thread, for the thread to acknowledge the interrupt request and cancel itself, although there are times when it cancels itself without completing the cycle.
A critical appreciation of this example would certainly be appreciated since this is the first time I use Callable and Future.