Home  >  Article  >  Java  >  What is the importance of thread priority in Java?

What is the importance of thread priority in Java?

王林
王林forward
2023-08-27 08:25:06887browse

What is the importance of thread priority in Java?

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:

MAX_PRIORITY

This is the highest thread priority, with a value of 10.

NORM_PRIORITY

This is the default thread priority, the value is 5.

MIN_PRIORITY

This is the lowest thread priority, with a value of 1.

Syntax

public final int getPriority()

Example

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>);
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete