GreeterThread.java

Download this source file

// GreeterThread.java - Creating simple threads.
// GreeterThread objects have a "greet" method that takes a name and
// greets that person after a pause of up to one-half second.  This code
// says hello and good-bye to a person 10 times, in separate threads.
//
// Written 2004 by Wayne Pollock, Tampa Florida USA.  All Rights Reserved.

import java.util.*;

class GreeterThread
{
   private String message;  // The greeting to use.
   private Random RNG = new Random();  // RNG = (Pseudo)Random Number Generator.

   public GreeterThread ( String message )
   {
      this.message = message;
   }

   public void greet ( String name )
   {
      pause( 500 );  // Random delay, up to one-half second.
      System.err.println( message + " " + name );
   }

   private void pause ( int maxDelay )  // pause for maxDelay milliseconds.
   {
      int delay = RNG.nextInt( maxDelay );
      try { Thread.sleep( delay ); }
      catch ( InterruptedException ignored ) {}
   }


   public static void main ( String [] args )
   {
      final GreeterThread meet = new GreeterThread( "Howdy!" );
      final GreeterThread leave = new GreeterThread( "Good-bye!" );

      Thread meetThread = new Thread ( new Runnable()
         {  public void run ()
            {  for ( int i = 1; i <= 10; ++i )
               {  if ( i < 10 ) System.out.print( " " );
                  System.out.print( i + ": " );
                  meet.greet( "Mojo Jojo" );
               }
            }
         }
      );
      
      Thread leaveThread = new Thread ( new Runnable()
         {  public void run ()
            {  for ( int i = 1; i <= 10; ++i )
               {  if ( i < 10 ) System.out.print( " " );
                  System.out.print( i + ": " );
                  leave.greet( "Mojo Jojo" );
               }
            }
         }
      );

      meetThread.start();
      leaveThread.start();
   }
}