Java Thread How to - Make threads end in same order they started with an Executor








Question

We would like to know how to make threads end in same order they started with an Executor.

Answer

//from  w ww .j a va 2 s  .c  om
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
  static int MAX_THREADS = 10;

  public static void main(String[] args) throws Exception {
    System.out.println("Thread pool size = " + MAX_THREADS);
    ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
    Future previousFuture = null;
    for (int i = 0; i < MAX_THREADS; i++) {
      JobRunnable job = new JobRunnable(i, previousFuture);
      previousFuture = executor.submit(job);
    }
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    System.out.println("Program done.");
  }
}

class JobRunnable implements Runnable {
  int _lineIdx;
  Future f;

  public JobRunnable(int lineIdx, Future previousFuture) {
    _lineIdx = lineIdx;
    f = previousFuture;
  }

  public void run() {
    try {
      Thread.sleep(1000);
      String currentThreadName = Thread.currentThread().getName();
      System.out.println("Thread " + currentThreadName
          + " is done with its work on line " + _lineIdx);
      if (f != null) {
        System.out.println("Thread " + currentThreadName
            + " will wait for future " + f + " before printing its results.");
        f.get();
      }
      System.out.println("RESULT: " + _lineIdx + " (Printed on Thread "
          + currentThreadName + ")");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}