Thread Mechanism One: Example

1. Counter.java: (Download Source)

public class Counter extends Thread {
  private static int totalNum = 0;  // class-wide visibility
  private int currentNum, loopLimit;

  public Counter(int loopLimit) {
    this.loopLimit = loopLimit;
    currentNum = totalNum++;
  }

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

  /** When run finishes, the thread exits. */
  
  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. CounterTest.java: (Download Source)

public class CounterTest {
  public static void main(String[] args) {
    Counter c1 = new Counter(5);
    Counter c2 = new Counter(5);
    Counter c3 = new Counter(5);
    c1.start();
    c2.start();
    c3.start();
  }
}

3. CounterTest Output

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

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