Java Thread How to - Use Future and Callable to work with subtasks








Question

We would like to know how to use Future and Callable to work with subtasks.

Answer

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
//from   w w w  .j a v  a 2  s  . com
public class Main {
  int[] itemsToBeProcessed;
  public static void main(String[] args) {
    new Main(32).processUsers(4);
  }

  public Main(int size) {
    itemsToBeProcessed = new int[size];
  }
  public void processUsers(int numOfWorkerThreads) {
    ExecutorService threadPool = Executors
        .newFixedThreadPool(numOfWorkerThreads);
    int chunk = itemsToBeProcessed.length / numOfWorkerThreads;
    int start = 0;
    List<Future> tasks = new ArrayList<Future>();
    for (int i = 0; i < numOfWorkerThreads; i++) {
      tasks.add(threadPool.submit(new WorkerThread(start, start + chunk)));
      start = start + chunk;
    }
    // join all worker threads to main thread
    for (Future f : tasks) {
      try {
        f.get();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    threadPool.shutdown();
    while (!threadPool.isTerminated()) {
    }
  }
}
class WorkerThread implements Callable {
  int startIndex, endIndex;
  public WorkerThread(int startIndex, int endIndex) {
    this.startIndex = startIndex;
    this.endIndex = endIndex;
  }
  @Override
  public Object call() throws Exception {
    for (int currentUserIndex = startIndex; currentUserIndex < endIndex; currentUserIndex++) {
      // Add your logic here
      System.out.println(currentUserIndex
          + " is the user being processed in thread "
          + Thread.currentThread().getName());
    }
    return null;
  }
}

The code above generates the following result.