/* * ThreadExample3 * by Robert Keller * * Two threads are created. Each sleeps for an amount 'delay' of * milliseconds, then wakes up and prints its step number. * * As soon as thread 2 terminates, thread 1 is interrupted, * and it then terminates itself. */ class ThreadExample3 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 ThreadExample3 with the specified ID and delay value. */ public ThreadExample3(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(); } /** * Interrupt this thread. */ public void interrupt() throws InterruptedException { myThread.interrupt(); } /** * 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( InterruptedException e ) { System.out.println("thread " + myID + " interrupted at step " + step); return; } catch( Exception e ) { } } } public static void main(String arg[]) { ThreadExample3 thread1 = new ThreadExample3(1, 1000, 10); ThreadExample3 thread2 = new ThreadExample3(2, 500, 10); thread1.start(); thread2.start(); try { thread2.join(); System.out.println("thread 2 terminates"); thread1.interrupt(); System.out.println("thread 1 terminates"); } catch( InterruptedException e ) { } } }