Chapter 15 Multithreading 845 run method. Variable sleepTime

Chapter 15 Multithreading 845 run method. Variable sleepTime stores a random integer value chosen when the program creates a PrintThreadobject. Each PrintThreadobject sleeps for the amount of time specified by its sleepTime, then outputs its name. The PrintThread constructor (lines 38 48) initializes sleepTime to a random integer between 0 and 4999 (0 to 4.999 seconds). Then, the constructor outputs the name of the thread and the value of sleepTime to show the values for the particular Print- Thread being constructed. The name of each thread is specified as a String argument to the PrintThread constructor and is passed to the superclass constructor at line 40. [Note: It is possible to allow class Thread to choose a name for your thread by using the Threadclass s default constructor. 1 // Fig. 15.3: ThreadTester.java 2 // Show multiple threads printing at different intervals. 3 4 public class ThreadTester { 5 6 // create and start threads 7 public static void main( String args[] ) 8 { 9 PrintThread thread1, thread2, thread3, thread4; 10 11 // create four PrintThread objects 12 thread1 = new PrintThread( “thread1″ ); 13 thread2 = new PrintThread( “thread2″ ); 14 thread3 = new PrintThread( “thread3″ ); 15 thread4 = new PrintThread( “thread4″ ); 16 17 System.err.println( “nStarting threads” ); 18 19 // start executing PrintThreads 20 thread1.start(); 21 thread2.start(); 22 thread3.start(); 23 thread4.start(); 24 25 System.err.println( “Threads startedn” ); 26 } 27 28 } // end class ThreadTester 29 30 // Each object of this class picks a random sleep interval. 31 // When a PrintThread executes, it prints its name, sleeps, 32 // prints its name again and terminates. 33 class PrintThread extends Thread { 34 private int sleepTime; 35 36 // PrintThread constructor assigns name to thread 37 // by calling superclass Thread constructor Fig. 15.3Multiple threads printing at random intervals (part 1 of 3). Fig. 15.3
We recommend high quality webhost to host and run your jsp application: christian web host services.

Leave a Reply