Threads
Manipulate threads
Set a thread's priority
How to set a thread's priority
- If two or more runnable threads have different priorities, the thread scheduler executes the threads with the highest priority setting first.
- If two or more runnable threads have the same priority, the thread scheduler determines which thread to execute next. On most platforms, the threads are executed in a round-robin order.
- A thread can't yield to a thread with a lower priority.
- By default, every thread is given the priority of the thread that created it. If a thread is created from the main thread, it's given a priority of 5 by default.
- Since thread scheduling relies on the underlying system, the final result may vary depending on the platform.
The setPriority method of the Thread class
Method | Description | setPriority(int) | Changes this thread's priority to an int value from 1 to 10. |
---|
Fields of the Thread class used to set thread priorities
Field | Description | MAX_PRIORITY | The maximum priority of any thread (an int value of 10). | MIN_PRIORITY | The minimum priority of any thread (an int value of 1). | NORM_PRIORITY | The default priority of any thread (an int value of 5). |
---|
A version of the Count Down application that sets thread priorities
public class CountDownPrioritiesApp { public static void main(String[] args) { Thread count1 = new CountDownEven(); // instantiate the threads Thread count2 = new CountDownOdd(); count1.setPriority(Thread.MIN_PRIORITY); // set the thread priorities count2.setPriority(Thread.MAX_PRIORITY); count1.start(); // start the threads count2.start(); } }
Console output from the Count Down application that sets thread priorities
Thread-1 Count 9 Thread-1 Count 7 Thread-1 Count 5 Thread-1 Count 3 Thread-1 Count 1 Thread-0 Count 10 Thread-0 Count 8 Thread-0 Count 6 Thread-0 Count 4 Thread-0 Count 2 Press any key to continue . . .