/** * File $CISC370HOME/example-progs/threads/vacationRace/version1/SimpleThread.java * * This code is based on an example from"The Java Tutorial" * by Campione and Walrath. It implements threads by subclassing the * java.lang.Thread class whereas version 2 uses threads by implementing * the interface Runnable. */ // The Thread class is in the java.lang package that is automatically // included in all Java programs. class SimpleThread extends Thread { public SimpleThread( String str ) // Constructor w name for thread { super( str ); } // Must override this method. It is called via start(). public void run() { for (int i = 0; i < 10; i++) { // getName is a instance method from the Thread class System.out.println( i + " " + getName() ); try { // sleep() is a static method from the class Thread sleep( (int)(Math.random()*5000) ); } catch ( InterruptedException e ) {} } System.out.println( "DONE! " + getName() ); // The thread dies a natural death when run() completes } public static void main( String arg[] ) { // Every thread must be created (w new) and started (w // the start method) to have any effect. // The start method creates the system resources necessary to // run the thread, schedules the thread to run, and calls // the thread's run method. // These threads help to determine where to take your vacation. // They "race" from 0-9 with each sleeping for a random period // of time between each increment of their counter. The first // one to win determines the place for you to go on your vacation! // Every thread has a name, in this case the names are Hawaii // and Fiji. new SimpleThread( "Hawaii" ).start(); // start() sets up a thread new SimpleThread( "Fiji" ).start(); // and then invokes run() } }