import java.util.List;
import java.util.Vector;

/**
 * Demo of the simplest possible multi-thread configuration.  Essentially just
 * illustrates creating a new thread by extending java.lang.Thread and
 * overriding the run() method.  The threads produced in this program are all
 * independent and have no real interaction, so no synchronization is
 * required.
 *
 * @author Terran Lane
 * @version 1.0
 */
public class ThreadDemo0 {

  public static void main(String[] args) {
    if (args.length<1) {
      System.err.println("Usage:");
      System.err.println("\tThreadDemo nThreads");
      System.exit(1);
    }
    ThreadDemo0 td=new ThreadDemo0(Integer.valueOf(args[0]).intValue());
  }

  /* ******************** end of public interface ******************** */

  private List thrList;
  private static final int MAX_ITER=5;

  private ThreadDemo0(int nt) {
    if (nt<=0) {
      throw new IllegalArgumentException("Number of threads must be >0");
    }
    thrList=new Vector(nt);
    for (int i=0;i<nt;++i) {
      Thread t=new _localThread("Thread[" + i + "]",(i+1)*700);
      thrList.add(t);
      t.start();
    }
  }

  private static class _localThread extends Thread {
    public _localThread(String name,int delay) {
      assert name!=null;
      _name=name;
      _delay=delay;
      _startTime=System.currentTimeMillis();
    }

    public void run() {
      int nIter=0;
      System.out.println("Starting " + _name);
      while (nIter++<MAX_ITER) {
	try {
	  sleep(_delay);
	}
	catch (InterruptedException e) {
	  // This shouldn't happen, but just in case...
	  System.err.println(_name + "interrupted.  Terminating.");
	  return;
	}
	long now=System.currentTimeMillis();
	System.out.println(_name + ": After " + nIter + " iteration(s); " +
			   " elapsed time=" + (now-_startTime) + "ms");
      }
      // when run() returns, this thread terminates
    }

    /* *************** end of public interface *************** */

    private final String _name;
    private final int _delay;
    private final long _startTime;
  }
}
