GreeterThread.java
Download GreeterThread.java
1: // GreeterThread.java - Creating simple threads.
2: // GreeterThread objects have a "greet" method that takes a name and
3: // greets that person after a pause of up to one-half second. This code
4: // says hello and good-bye to a person 10 times, in separate threads.
5: //
6: // Written 2004 by Wayne Pollock, Tampa Florida USA. All Rights Reserved.
7:
8: import java.util.*;
9:
10: class GreeterThread
11: {
12: private String message; // The greeting to use.
13: private Random RNG = new Random(); // RNG = (Pseudo)Random Number Generator.
14:
15: public GreeterThread ( String message )
16: {
17: this.message = message;
18: }
19:
20: public void greet ( String name )
21: {
22: pause( 500 ); // Random delay, up to one-half second.
23: System.err.println( message + " " + name );
24: }
25:
26: private void pause ( int maxDelay ) // pause for maxDelay milliseconds.
27: {
28: int delay = RNG.nextInt( maxDelay );
29: try { Thread.sleep( delay ); }
30: catch ( InterruptedException ignored ) {}
31: }
32:
33:
34: public static void main ( String [] args )
35: {
36: final GreeterThread meet = new GreeterThread( "Howdy!" );
37: final GreeterThread leave = new GreeterThread( "Good-bye!" );
38:
39: Thread meetThread = new Thread ( new Runnable()
40: { public void run ()
41: { for ( int i = 1; i <= 10; ++i )
42: { if ( i < 10 ) System.out.print( " " );
43: System.out.print( i + ": " );
44: meet.greet( "Mojo Jojo" );
45: }
46: }
47: }
48: );
49:
50: Thread leaveThread = new Thread ( new Runnable()
51: { public void run ()
52: { for ( int i = 1; i <= 10; ++i )
53: { if ( i < 10 ) System.out.print( " " );
54: System.out.print( i + ": " );
55: leave.greet( "Mojo Jojo" );
56: }
57: }
58: }
59: );
60:
61: meetThread.start();
62: leaveThread.start();
63: }
64: }