26.8. Chapter Summary

 
[Page 777 ( continued )]

24.4. The Thread Class

The Thread class contains the constructors for creating threads for tasks , and the methods for controlling threads, as shown in Figure 24.4.

Figure 24.4. The Thread class contains the methods for controlling threads.

Note

Since the Thread class implements Runnable , you could declare a class that extends Thread and implements the run method, as shown in Figure 24.5(a), and then create an object from the class and invoke its start method in a client program to start the thread, as shown in Figure 24.5(b).

Figure 24.5. Define a thread class by extending the Thread class.
(This item is displayed on page 778 in the print version)

This approach is, however, not recommended, because it mixes the task and the mechanism of running the task. Separating the task from the thread is a preferred design.


Note

The Thread class also contains the stop() , suspend() , and resume() methods. As of Java 2, these methods are deprecated (or outdated ) because they are known to be inherently unsafe. Instead of using the stop() method, you should assign null to a Thread variable to indicate that it is stopped .


[Page 778]

You can use the yield() method to temporarily release time for other threads. For example, suppose you modify the code in the run() method (lines 53 “57 in PrintNum in TaskThreadDemo.java) in Listing 24.1 as follows :

   public void   run() {   for   (   int   i =   1   ; i <= lastNum; i++) {     System.out.print(   " "   + i);  Thread.yield();  } } 

Every time a number is printed, the print100 thread is yielded. So each number is followed by some characters .

The sleep(long mills) method puts the thread to sleep for the specified time in milliseconds to allow other threads to execute. For example, suppose you modify the code in lines 53 “57 in TaskThreadDemo.java in Listing 24.1 as follows:

   public void   run() {  try {    for   (   int   i =   1   ; i <= lastNum; i++) {     System.out.print(   " "   + i);   if   (i >=   50   ) ;  Thread.sleep(1)  ;     }   }  catch (InterruptedException ex) {  } } 

Every time a number ( >= 50 ) is printed, the print100 thread is put to sleep for 1 millisecond.

The sleep method may throw an InterruptedException , which is a checked exception. Such an exception may occur when a sleeping thread's interrupt() method is called. The interrupt() method is very rarely invoked on a thread, so an InterruptedException is unlikely to occur. But since Java forces you to catch checked exceptions, you have to put it in a try-catch block. If a sleep method is invoked in a loop, you should wrap the loop in a try-catch block, as shown in (a) below. If the loop is outside the try-catch block, as shown in (b), the thread may continue to execute even though it is being interrupted .


[Page 779]

You can use the join() method to force one thread to wait for another thread to finish. For example, suppose you modify the code in lines 53 “57 in TaskThreadDemo.java in Listing 24.1 as follows:

A new thread4 is created. It prints character c forty times. The numbers from 50 to 100 are printed after thread thread4 is finished.

Java assigns every thread a priority. By default, a thread inherits the priority of the thread that spawned it. You can increase or decrease the priority of any thread by using the setPriority method, and you can get the thread's priority by using the getPriority method. Priorities are numbers ranging from 1 to 10 . The Thread class has the int constants MIN_PRIORITY , NORM_PRIORITY , and MAX_PRIORITY , representing 1 , 5 , and 10 , respectively. The priority of the main thread is Thread.NORM_PRIORITY .

The JVM always picks the currently runnable thread with the highest priority. If several runnable threads have equally high priorities, the CPU is allocated to all of them in round- robin fashion. A lower-priority thread can run only when no higher-priority threads are running. For example, suppose you insert the following code in line 16 in TaskThreadDemo.java in Listing 24.1:

  print100.setPriority(Thread.MAX_PRIORITY);  

The print100 thread will be finished first.

Tip

The priority numbers may be changed in a future version of Java. To minimize the impact of any changes, use the constants in the Thread class to specify thread priorities.


Tip

A thread may never get a chance to run if there is always a higher-priority thread running or a same-priority thread that never yields. This situation is known as contention or starvation . To avoid contention, the thread with high priority must periodically invoke the sleep or yield method to give a thread with a lower or the same priority a chance to run.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net