/*
 *  ==============================================================
 *  Counter.java : The main class that constructs an instance of Thread that counts up to a limit
 *  with random pauses in between each count.
 *
 *  Adapted from : Hall M., Core Web Programming, 1997
 *  Modified by : Vasilios Lagakos                     March, 2001
 *  ==============================================================
 */


public class Counter2 implements Runnable {
  private static int totalNum = 0;
  private int currentNum, loopLimit;

  public Counter2(int loopLimit) {
    this.loopLimit = loopLimit;
    currentNum = totalNum++;
/* Construct an instance of Thread, passing the current class (i.e. the Runnable) as an argument. */
    Thread t = new Thread(this);
    t.start(); // Calls back to run method in "this"
  }

  private void pause(double seconds) {
    try { Thread.sleep(Math.round(1000.0*seconds)); }
    catch(InterruptedException ie) {}
  }
  

/* Thread behavior in following method. If you want to access thread instance (e.g. to get private per
   thread data), use Thread.currentThread() */ 
  public void run() {
    for(int i=0; i<loopLimit; i++) {
      System.out.println("Counter " + currentNum
                         + ": " + i);
      pause(Math.random()); // Sleep for up to 1 second
    }
  }
}
