/* * ThreadExample2 * by Robert Keller * * Two threads are created. Each sleeps for an amount 'delay' of * milliseconds, then wakes up and prints its step number. * Each runs for a designated number of steps. * * The main program awaits for each thread to terminate, using 'join', * and prints when termination occurs. */ class ThreadExample2 implements Runnable { Thread myThread; // Thread object for control int myID; // Identifier for this "thread" int step; // Step number of this "thread" int totalSteps; // Total number of steps int delay; // delay milliseconds /** * Construct a ThreadExample2 with the specified ID and delay value. */ public ThreadExample2(int myID, int delay, int totalSteps) { this.myID = myID; this.delay = delay; this.totalSteps = totalSteps; myThread = new Thread(this); step = 1; } /** * Start this thread. * The run method will be called. */ public void start() { myThread.start(); } /** * Join with this thread, meaning wait until it has completed. */ public void join() throws InterruptedException { myThread.join(); } /** * The run() method required to implement the Runnable interface. */ public void run() { while( step <= totalSteps ) { // 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[]) { ThreadExample2 thread1 = new ThreadExample2(1, 1000, 10); ThreadExample2 thread2 = new ThreadExample2(2, 500, 10); thread1.start(); thread2.start(); try { thread2.join(); System.out.println("thread 2 terminates"); thread1.join(); System.out.println("thread 1 terminates"); } catch( InterruptedException e ) { } } }