Chapter 15 Multithreading 847 Name: (Free web design) thread1; sleep: 2753

Chapter 15 Multithreading 847 Name: thread1; sleep: 2753 Name: thread2; sleep: 3199 Name: thread3; sleep: 2797 Name: thread4; sleep: 4639 Starting threads Threads started thread1 going to sleep thread2 going to sleep thread3 going to sleep thread4 going to sleep thread1 done sleeping thread3 done sleeping thread2 done sleeping thread4 done sleeping Fig. 15.3Multiple threads printing at random intervals (part 3 of 3). Fig. 15.3 When the program invokes a PrintThread s start method (inherited from Thread), the PrintThread object enters the ready state. When the system assigns a processor to the PrintThread object, it enters the running state and its run method begins execution. Method run (lines 51 69) prints a String in the command window indicating that the thread is going to sleep (line 55), then invokes the sleepmethod (line 58) to place the thread into a sleeping state. At this point, the thread loses the processor, and the system allows another thread to execute. When the thread awakens, it is placed in a ready state again until the system assigns to the thread. When the PrintThread object enters the running state again, line 68 outputs the thread s name (indicating that the thread is done sleeping), the run method terminates and the thread object enters the dead state. Note that method sleepcan throw a checked InterruptedException (if another thread invokes the sleeping thread s interruptmethod); therefore, sleep must be called in a tryblock (in this example, we simply output the Stringrepresentation of the exception if one occurs). Note that this example uses System.err rather than System.out to output lines of text. System.err represents the standard error object, which outputs error messages (normally to the command window). System.out performs buffered output it is possible that a message output with System.out will not be output immediately. On the other hand, System.err uses unbuffered output messages appear immediately when they are output. Using System.err in a multithreaded program helps ensure that the messages from our program are output in the correct order. Class ThreadTester s main method (lines 7 26) creates four objects of class PrintThread (lines 12 15) and invokes the Thread class start method on each one (lines 20 23) to place all four PrintThreadobjects in a ready state. Note that the program terminates execution when the last PrintThread awakens and prints its name. Also, note that the main method (i.e., the main thread of execution) terminates after starting the four PrintThreads, but the application does not terminate until the last thread dies.
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Leave a Reply