/** * File $CISC370HOME/example-progs/threads/vacationRace/version2/SimpleThread.java * * This code is based on an example from "The Java Tutorial" * by Campione and Walrath. It uses threads by implementing the * interface java.lang.Runnable whereas version 1 implements threads * by subclassing the Thread class. */ class SimpleThread implements Runnable { String threadName = null; // Instance variable public SimpleThread( String str ){ // Constructor w name for thread threadName = str; } public String getName(){ return threadName; } public void start(){ new Thread( this ).start(); // Create and start new thread } // Must pass Runnable obj "this" to // the Thread constructor public void run() // The run() method for the thread { for (int i = 0; i < 10; i++) { System.out.println( i + " " + getName() ); try { // sleep() is a static method from the class Thread Thread.sleep( (int)(Math.random()*5000) ); } catch ( InterruptedException e ) {} } System.out.println( "DONE! " + getName() ); } public static void main( String arg[] ) { // 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(); new SimpleThread( "Fiji" ).start(); } }