In a multi-threaded application, each thread is assigned a priority. Processors are assigned to threads by the thread scheduler based on their priority (i.e., the highest priority thread is assigned a processor first, and so on). The default priority of a thread is 5. We can use the getPriority() method of the Thread class to get the priority of the thread.
In the Thread class, three static values are defined to represent the priority of the thread:
This is the highest thread priority, with a value of 10.
This is the default thread priority, the value is 5.
This is the lowest thread priority, with a value of 1.
public final int getPriority()
public class ThreadPriorityTest extends Thread { public static void main(String[]args) { ThreadPriorityTest thread1 = new ThreadPriorityTest(); ThreadPriorityTest thread2 = new ThreadPriorityTest(); ThreadPriorityTest thread3 = new ThreadPriorityTest(); System.out.println("Default thread priority of thread1: " + thread1.<strong>getPriority</strong>()); System.out.println("Default thread priority of thread2: " + thread2.<strong>getPriority</strong>()); System.out.println("Default thread priority of thread3: " + thread3.<strong>getPriority</strong>()); thread1.setPriority(8); thread2.setPriority(3); thread3.setPriority(6); System.out.println("New thread priority of thread1: " + thread1.<strong>getPriority()</strong>); System.out.println("New thread priority of thread2: " + thread2.<strong>getPriority()</strong>); System.out.println("New thread priority of thread3: " + thread3.<strong>getPriority()</strong>); } }
Default thread priority of thread1: 5 Default thread priority of thread2: 5 Default thread priority of thread3: 5 New thread priority of thread1: 8 New thread priority of thread2: 3 New thread priority of thread3: 6
The above is the detailed content of What is the importance of thread priority in Java?. For more information, please follow other related articles on the PHP Chinese website!