Priority of a Thread in Java

When using multithreading, the operating system’s scheduler assigns each thread a different level of urgency or significance before it is run. Threads with higher priority values get more CPU time than threads with lower priority values.

This prioritization can be used to control the order and frequency of thread execution, which is essential in systems with limited resources or real-time requirements. Every thread is given a priority. It should be noted that a Java programmer can explicitly assign a thread’s priority in a Java program in addition to the JVM.

Three constants are defined in the Thread class:

  • MIN_PRIORITY is an open static int.
  • NORM_PRIORITY is a public static int.
  • public static array MAX_PRIORITY

A thread has a priority of 5 by default (NORM_PRIORITY). MAX_PRIORITY is set to 10, while MIN_PRIORITY is set to 1.

thread priority

how to get and set a thread’s priority in Java:

  • getPriority() is a public, final int in Java.lang.The method Thread.getPriority() retrieves the given thread’s priority.
  • Ultimate public void The java.lang.Thread.setPriority() function sets the thread’s priority to the value specified by the argument newPriority. If the value of the input newPriority exceeds the minimum(1) and maximum(10) limit, this function throws an IllegalArgumentException.

Setter & Getter Thread Priority Method in Java

  • The java.lang. public final int getPriority() method.The priority of the specified thread is returned by the Thread.getPriority() function.
  • ultimate public void setPriority(int newPriority): The thread’s priority is updated or assigned using the java.lang.Thread.setPriority() function. If the value of newPriority exceeds the range of 1 (minimum) to 10 (maximum), the method throws an IllegalArgumentException.

Program:

Example 1:

import java.lang.*;  
public class TechVidvan extends Thread   
{  
public void run()  
{  
System.out.println("Inside the run() method");  
}  
public static void main(String argvs[])  
{  
TechVidvan tv1 = new TechVidvan();  
TechVidvan tv2 = new TechVidvan(); 
TechVidvan tv3 = new TechVidvan();  
System.out.println("Priority of the thread tv1 is : " + tv1.getPriority());  
System.out.println("Priority of the thread tv2 is : " + tv2.getPriority());  
System.out.println("Priority of the thread tv2 is : " + tv2.getPriority());  
tv1.setPriority(6);  
tv2.setPriority(3);  
tv3.setPriority(9);  
System.out.println("Priority of the thread tv1 is : " + tv1.getPriority());  
System.out.println("Priority of the thread tv2 is : " + tv2.getPriority());  
System.out.println("Priority of the thread tv3 is : " + tv3.getPriority());  
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());  
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
Thread.currentThread().setPriority(10);   
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
}
}

Output:

Priority of the thread tv1 is: 5
Priority of the thread tv2 is: 5
Priority of the thread tv2 is: 5
Priority of the thread tv1 is: 6
Priority of the thread tv2 is : 3
Priority of the thread tv3 is: 9
Currently Executing The Thread: main
priority of the main thread is: 5

Explanation:

We are aware that when it comes to thread execution, a thread with a high priority will take precedence over threads with a lower priority. Two threads may, however, share the same priority under other circumstances.

The Java thread scheduler does all of the work required to manage the threads. To understand what will happen if two threads have the same priority, consider the scenario that follows.

Example 2:

import java.lang.*;  
public class TechVidvan extends Thread   
{  
public void run()  
{  
System.out.println("Inside the run() method");  
}  
public static void main(String argvs[])  
{  
Thread.currentThread().setPriority(7);  
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
TechVidvan tv1 = new TechVidvan();  
System.out.println("Priority of the thread tv1 is : " + tv1.getPriority());  
}  
}

Output:

Priority of the main thread is: 7
Priority of the thread tv1 is: 7

Explanation:

The algorithm used by the thread scheduler (such as First Come, First Serve, Round-Robin, etc.) will then determine how things are carried out.

IllArgumentException Example:

We are aware that the IllegalArgumentException is thrown if the value of the newPriority parameter of the getPriority() function is outside the range (1 to 10). Let’s use an illustration to observe this.

Program:

import java.lang.*;  
public class TechVidvan extends Thread   
{  
public static void main(String argvs[])  
{  
Thread.currentThread().setPriority(17);  
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
}  
}

Output:

Exception in thread “main” java.lang.IllegalArgumentException
at java.base/java.lang.Thread.setPriority(Thread.java:1136)at TechVidvan.main(IllegalArgumentException.java:7)

Issues:

  • Class Naming Conflict: You’ve named your class IllegalArgumentException, which conflicts with the built-in Java class IllegalArgumentException. This causes confusion and can lead to errors.
  • Invalid Priority Value: You’re trying to set the priority of the main thread to 17. In Java, thread priority values typically range from 1 (minimum) to 10 (maximum). Using a value of 17 is invalid and would likely result in an IllegalArgumentException.

Explanation:

  • You are importing the java.lang package, even though classes from this package are already imported automatically.
  • A class called IllegalArgumentException was generated by you. To avoid confusion and mistakes, it’s not a good idea to use names of existing classes for your own classes.
  • You’re trying to set the priority of the current (main) thread in the main method to 17, which is beyond the acceptable priority range of 1 to 10.
  • Finally, you print out the priority of the main thread, which, if it had been a valid number, would have been set to 17. The actual result, however, is unknown due to the invalid value and is dependent on how the Java runtime environment behaves.

Thread Execution

A scheduling method known as fixed-priority pre-emptive scheduling is supported by the JVM. Every Java thread has a priority, and the JVM gives the highest priority thread the most attention first.

A Thread inherits its default priority when it is created. The JVM chooses and executes the Runnable thread with the highest priority when several threads are prepared to run. The lower priority threads will run in the event that this thread is terminated or becomes unrunnable. The JVM will execute threads in FIFO order if they have the same priority.

There are two situations that may result in the execution of a separate thread:

  • The ability to execute a thread with a greater priority than the one now running.
  • The current thread either yields (briefly pauses to allow other threads) or leaves the runnable state.
  • In general, the thread with the highest priority is active at all times. But occasionally, the thread scheduler may decide to execute low-priority threads in order to prevent starvation.

Summary

Java Thread priority is crucial for managing the execution order and resource allocation in multi-threaded applications. Without explicit priority settings, threads may execute in an unpredictable manner. By assigning priority levels to threads, developers can influence the order and frequency of thread execution, which can be especially useful in scenarios where certain threads require immediate attention or real-time responsiveness. However, the actual behavior can vary based on the underlying operating system and scheduler implementation.