Free web hosting with ftp - 846 Multithreading Chapter 15 38 public PrintThread( String

846 Multithreading Chapter 15 38 public PrintThread( String name ) 39 { 40 super( name ); 41 42 // sleep between 0 and 5 seconds 43 sleepTime = (int) ( Math.random() * 5000 ); 44 45 // display name and sleepTime 46 System.err.println( 47 “Name: ” + getName() + “; sleep: ” + sleepTime ); 48 } 49 50 // control thread’s execution 51 public void run() 52 { 53 // put thread to sleep for a random interval 54 try { 55 System.err.println( getName() + ” going to sleep” ); 56 57 // put thread to sleep 58 Thread.sleep( sleepTime ); 59 } 60 61 // if thread interrupted during sleep, catch exception 62 // and display error message 63 catch ( InterruptedException interruptedException ) { 64 System.err.println( interruptedException.toString() ); 65 } 66 67 // print thread name 68 System.err.println( getName() + ” done sleeping” ); 69 } 70 71 } // end class PrintThread Name: thread1; sleep: 3593 Name: thread2; sleep: 2653 Name: thread3; sleep: 4465 Name: thread4; sleep: 1318 Starting threads Threads started thread1 going to sleep thread2 going to sleep thread3 going to sleep thread4 going to sleep thread4 done sleeping thread2 done sleeping thread1 done sleeping thread3 done sleeping Fig. 15.3Multiple threads printing at random intervals (part 2 of 3). Fig. 15.3
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Leave a Reply