16.3. Thread Priorities
All threads have a priority that determines which thread is executed when several threads are waiting for their turn. This makes it possible to give one thread more access to processor resources than another. Let's consider an elementary example of how this could be used. Suppose you have one thread in a program that requires all the processor resources—some solid long-running calculation—and some other threads that require relatively few resources. By making the thread that requires all the resources a low-priority thread, you ensure that the other threads are executed promptly, while the processor bound thread can make use of the processor cycles that are left over after the others have had their turn.
The possible values for thread priority are defined in static data members of the class Thread. These members are of type int and are declared as final. The maximum thread priority is defined by the member MAX_PRIORITY, which has the value 10. The minimum priority is MIN_PRIORITY, defined as 1. The value of the default priority that is assigned to the main thread in a program is NORM_PRIORITY, which is set to 5. When you create a thread, its priority will be the same as that of the thread that created it.
You can modify the priority of a thread by calling the setPriority() method for the Thread object. This method accepts an argument of type int that defines the new priority for the thread. An IllegalArgumentException will be thrown if you specify a priority ...
Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.