Java Thread How to - Use ExecutorService to manage Callable








Question

We would like to know how to use ExecutorService to manage Callable.

Answer

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*from   w w w.  j ava 2  s  . co m*/
class WordLengthCallable implements Callable<Integer> {
  private Random random = new Random();

  public Integer call() throws InterruptedException {
    int sleepTime = (2 + random.nextInt(16)) * 500;
    Thread.sleep(sleepTime);
    return sleepTime;
  }
}
public class Main {
  public static void main(String[] args) throws Exception {
    int THREAD_COUNT = 4;
    ExecutorService execService = Executors.newFixedThreadPool(THREAD_COUNT);
    CompletionService<Integer> completionService = new ExecutorCompletionService<>(
        execService);

    for (int i = 0; i < THREAD_COUNT; i++) {
      completionService.submit(new WordLengthCallable());
    }
    execService.shutdown();
    while (!execService.isTerminated()) {
        int result = completionService.take().get().intValue();
        System.out.println("Result is: " + result);
    }
    Thread.sleep(1000);
    System.out.println("done!");
  }
}

The code above generates the following result.