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








Question

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

Answer

/*from   w  w w  .j  a va2 s.c  o m*/
public class Main {
  public static void main(String[] args) throws Exception {
    Thread previousThread = null;
    for (int i = 0; i < 20; i++) {
      JobRunnable job = new JobRunnable(i, previousThread);
      Thread thread = new Thread(job, "T-" + i);
      thread.start();
      previousThread = thread;
    }
    if (previousThread != null) {
      previousThread.join();
    }
    System.out.println("Program done.");
  }
}

class JobRunnable implements Runnable {
  final int _lineIdx;
  final Thread t;

  public JobRunnable(int lineIdx, Thread threadToWaitForBeforePrinting) {
    _lineIdx = lineIdx;
    t = threadToWaitForBeforePrinting;
  }

  public void run() {
    try {
      String currentThreadName = Thread.currentThread().getName();
      if (t != null) {
        t.join();
      }
      Thread.sleep(3000);
      System.out.println("RESULT: " + _lineIdx + " " + " (Printed on Thread "
          + currentThreadName + ")");
    } catch (Exception e) {
      Thread.currentThread().interrupt();
    }
  }
}