What is the Thread.getPriority() method in Java?

Overview

The getPriority() method of the Thread classThe Thread class is used to run multiple processes or threads simultaneously. in Java is used to extract the priority of the .this thread. When we create a thread/process, the Thread scheduler in Java assigns some priority to it. The thread priority ranges from 1 to 10, while the default priority value of a thread is 5.

Note: The Thread scheduler assigns priority implicitly. The programmer can also set this priority explicitly by invoking the setPriority() method.

Syntax

The syntax for the getPriority() method is given below:


final int getPriority()  

Parameter values

This method does not take any parameter values.

Return value

This method returns an integer value. This value ranges from 1 to 10 as a priority number in the process priority queue.

Code example

Here, we have an example to demonstrate the working the getPriority() method:

// Program to use getPriority()
// Main class which extends Thread class
public class Main extends Thread {
public void run() {
System.out.println("Running thread name: "
+ Thread.currentThread().getName());
}
public static void main(String args[]) {
// create two threads
Main thread1 = new Main();
Main thread2 = new Main();
// chnage thread names
thread1.setName("thread1");
thread2.setName("thread2");
// print the default priority value of thread
System.out.println("thread1 priority : " + thread1.getPriority());
System.out.println("thread2 priority : " + thread2.getPriority());
// this will call the run() method
thread1.start();
thread2.start();
}
}

Code explanation

  • Lines 10–11: We create two threads by instantiating Main.class.
  • Lines 16–17: We get the threads’ default priority by invoking the getPriority() method for each thread. Keep in mind that the priority of the threads depends upon JVMJava Virtual Machine.
  • Lines 19–20: We invoke the start() method to start the execution of the threads.

Free Resources