Home > Java > javaTutorial > body text

What is the importance of thread priority in Java?

王林
Release: 2023-08-27 08:25:06
forward
898 people have browsed it

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()
Copy after login

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>);
   }
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!