Also available as ThreadPlay.java

/** 
 * Simple program using threads.
 *
 */


/**
 * class Counter is runnable, so we can turn a counter object into 
 * a thread (the run() method is run when this happens).
 *
 * This class assigns unique ids to each Counter object, and the run
 * method just counts to ten. Try using each of the run methods
 * (rename the one you want to be executed to "run()" ) to see what
 * happens to the thread scheduling
 */

class Counter implements Runnable { 
  static int id=0; 
  int myid; 
  int x;
  // n is how many times each thread counts.
  static final int n=3;

  public Counter() {
        myid = id++;
        x=0;
  }

  // this run is used to see what happens (to scheduling) when the
  // threads don't wait for anything (and never call yield).

  public void run() {
        while (x<n) {
          System.out.println("Counter["+myid + "]:  value is " + x );
          x++;
        }
  }


  // name this one run() to see what happens when each thread goes
  // to sleep regularly.
  public void run1() {
        try {
          while (x<n) {
                System.out.println("Counter["+myid + "]:  value is " + x );
                x++;
                // let another thread run
                Thread.currentThread().yield();
          }
          // uncomment this to see how having any thread alive keeps
          // the program from quitting
          if (myid==0) {
                System.out.println("I refuse to die!");
                while (true) {
                  // wait 100 ms.
                  Thread.currentThread().sleep(100);
                }
          }
        } catch (InterruptedException ie) {
          ie.printStackTrace();
        }
        
  }
}


class ThreadPlay {

  // creates 5 counter threads and sets them running.
  public static void main(String [] args) {
        for (int i=0;i<5;i++) {
          Thread t = new Thread( new Counter());
          t.start();
          System.out.println("Started thread " + i );
        }
        System.out.println("main is done - goodbye");
  }

}