public class ThreadTester
class PrintThread extends Thread
1: //ThreadTester.java
2: //Multiple threads printing at different intervals.
3:
4: public class ThreadTester
5: {
6: public static void main( String [] args )
7: {
8: System.out.println();
9:
10: // create and name each thread
11: PrintThread thread1 = new PrintThread( "thread1" );
12: PrintThread thread2 = new PrintThread( "thread2" );
13: PrintThread thread3 = new PrintThread( "thread3" );
14:
15: System.err.println( "Starting threads" );
16:
17: thread1.start(); // start thread1 and place it in ready state
18: thread2.start(); // start thread2 and place it in ready state
19: thread3.start(); // start thread3 and place it in ready state
20:
21: System.err.println( "Threads started, main ends\n" );
22:
23: } // end main
24:
25: } // end class ThreadTester
26:
27: // class PrintThread controls thread execution
28: class PrintThread extends Thread
29: {
30: private int sleepTime;
31:
32: // assign name to thread by calling superclass constructor
33: public PrintThread( String name )
34: {
35: super( name );
36:
37: // pick random sleep time between 0 and 5 seconds
38: sleepTime = ( int ) ( Math.random() * 5001 );
39: }
40:
41: // method run is the code to be executed by new thread
42: public void run()
43: {
44: // put thread to sleep for sleepTime amount of time
45: try
46: {
47: System.err.println(
48: getName() + " going to sleep for " + sleepTime );
49:
50: Thread.sleep( sleepTime );
51: }
52:
53: // if thread interrupted during sleep, print stack trace
54: catch ( InterruptedException exception )
55: {
56: exception.printStackTrace();
57: }
58:
59: // print thread name
60: System.err.println( getName() + " done sleeping" );
61: System.out.println();
62:
63: } // end method run
64:
65: } // end class PrintThread
66: