Thread Mechanism Two: Example

1. Counter2.java: (Download Source)

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

  public Counter2(int loopLimit) {
    this.loopLimit = loopLimit;
    currentNum = totalNum++;
    Thread t = new Thread(this);
    t.start();
  }

  private void pause(double seconds) {
    try { Thread.sleep(Math.round(1000.0*seconds)); }
    catch(InterruptedException ie) {}
  }
  
  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 
    }
  }
} 

2. Counter2Test.java: (Download Source)

public class Counter2Test {
  public static void main(String[] args) {
    Counter2 c1 = new Counter2(5);
    Counter2 c2 = new Counter2(5);
    Counter2 c3 = new Counter2(5);
  }
}


3. Counter2Test Output

Counter 0: 0
Counter 1: 0
Counter 2: 0
Counter 1: 1
Counter 1: 2
Counter 0: 1
Counter 1: 3
Counter 2: 1
Counter 0: 2
Counter 0: 3
Counter 1: 4
Counter 2: 2
Counter 2: 3
Counter 0: 4
Counter 2: 4


© 1996-99 Marty Hall, 1999 Lawrence M. Brown