Source of PrintThread.java


  1: // Fig. 23.4: PrintThread.java
  2: // PrintThread class sleeps for a random time from 0 to 5 seconds
  3: import java.util.Random;
  4: 
  5: public class PrintThread implements Runnable 
  6: {
  7:    private int sleepTime; // random sleep time for thread
  8:    private String threadName; // name of thread
  9:    private static Random generator = new Random();
 10:     
 11:    // assign name to thread
 12:    public PrintThread( String name )
 13:    {
 14:       threadName = name; // set name of thread
 15:         
 16:       // pick random sleep time between 0 and 5 seconds
 17:       sleepTime = generator.nextInt( 5000 );
 18:    } // end PrintThread constructor
 19:     
 20:    // method run is the code to be executed by new thread
 21:    public void run()
 22:    {
 23:       try // put thread to sleep for sleepTime amount of time 
 24:       {
 25:          System.out.printf( "%s going to sleep for %d milliseconds.\n", 
 26:             threadName, sleepTime );
 27:             
 28:          Thread.sleep( sleepTime ); // put thread to sleep
 29:       } // end try        
 30:       // if thread interrupted while sleeping, print stack trace
 31:       catch ( InterruptedException exception )
 32:       {
 33:          exception.printStackTrace();
 34:       } // end catch
 35:         
 36:       // print thread name
 37:       System.out.printf( "%s done sleeping\n", threadName );
 38:    } // end method run
 39: } // end class PrintThread
 40: 
 41: /**************************************************************************
 42:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 43:  * Pearson Education, Inc. All Rights Reserved.                           *
 44:  *                                                                        *
 45:  * DISCLAIMER: The authors and publisher of this book have used their     *
 46:  * best efforts in preparing the book. These efforts include the          *
 47:  * development, research, and testing of the theories and programs        *
 48:  * to determine their effectiveness. The authors and publisher make       *
 49:  * no warranty of any kind, expressed or implied, with regard to these    *
 50:  * programs or to the documentation contained in these books. The authors *
 51:  * and publisher shall not be liable in any event for incidental or       *
 52:  * consequential damages in connection with, or arising out of, the       *
 53:  * furnishing, performance, or use of these programs.                     *
 54:  *************************************************************************/