/* * ThreadExample1 * by Robert Keller * * A first example of Java threads, using "implements Runnable" * (as opposed to "extends Thread"). * * Two threads are created. Each sleeps for an amount 'delay' of * milliseconds, then wakes up and prints its step number. * * Due to difference in delay values, we expect thread 2 to progress * at roughly double the rate of thread 1. */ class ThreadExample1 implements Runnable { Thread myThread; // Thread object for control int myID; // Identifier for this "thread" int step; // Step number of this "thread" int delay; // delay milliseconds /** * Construct a ThreadExample1 with the specified ID and delay value. */ public ThreadExample1(int myID, int delay) { this.myID = myID; this.delay = delay; myThread = new Thread(this); step = 1; } /** * Start this thread. * The run method will be called. */ public void start() { myThread.start(); } /** * The run() method required to implement the Runnable interface. */ public void run() { while( true ) { // try/catch is needed because sleep can throw an exception. try { myThread.sleep(delay); System.out.println("thread " + myID + " is at step " + step); step++; } catch( Exception e ) { } } } public static void main(String arg[]) { ThreadExample1 thread1 = new ThreadExample1(1, 1000); ThreadExample1 thread2 = new ThreadExample1(2, 500); thread1.start(); thread2.start(); } }