Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Thread Priority In Java

Last Updated on July 20, 2023 by Mayank Dham

Multithreading is a powerful concept in Java that allows multiple threads to run concurrently within a single program. Multithreading allows developers to improve the performance, responsiveness, and efficiency of their applications. One aspect of thread management is assigning them priorities, which can influence their execution order and resource allocation. In this article, we will look at thread priorities in Java and how to use them effectively.
Understanding thread priority in Java
Each thread in Java is given a priority value ranging from 1 to 10, with 1 being the lowest and 10 being the highest. A new thread inherits the priority of its parent thread by default. The thread priorities are used as a hint by the Java Virtual Machine (JVM) to determine the order in which threads should be scheduled for execution. It is important to note, however, that thread priorities do not always have the same effect across different JVM implementations and operating systems.

Setting Thread Priority in Java

Java provides the setPriority() method in the Thread class to set the priority of a thread. Here’s an example:

Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());

thread1.setPriority(Thread.MIN_PRIORITY); // Setting lowest priority
thread2.setPriority(Thread.MAX_PRIORITY); // Setting highest priority

In this example, we create two threads, thread1 and thread2, and assign them different priorities using the setPriority() method. Thread.MIN_PRIORITY represents the lowest priority, while Thread.MAX_PRIORITY represents the highest priority.

Setter and Getter Methods of Thread Priority

Let us go over the thread priority setter and getter methods.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method changes or assigns the thread’s priority to newPriority. If the value newPriority is outside the range of 1 (minimum) to 10 (maximum), the method throws an IllegalArgumentException.

  1. public static int MIN_PRIORITY
  2. public static int NORM_PRIORITY
  3. public static int MAX_PRIORITY

A thread’s default priority is 5 (NORM_PRIORITY). The MIN_PRIORITY value is 1 and the MAX_PRIORITY value is 10.

Example of Priority of a Thread in

import java.lang.*;
public class ThreadPriorityExample extends Thread {
    public void run() {
        System.out.println("Inside the run() method");
    }
    public static void main(String argvs[]) {
        ThreadPriorityExample th1 = new ThreadPriorityExample();
        ThreadPriorityExample th2 = new ThreadPriorityExample();
        ThreadPriorityExample th3 = new ThreadPriorityExample();

        System.out.println("Priority of the thread th1 is : " + th1.getPriority());
        System.out.println("Priority of the thread th2 is : " + th2.getPriority());
        System.out.println("Priority of the thread th2 is : " + th2.getPriority());

        th1.setPriority(6);
        th2.setPriority(3);
        th3.setPriority(9);

        System.out.println("Priority of the thread th1 is : " + th1.getPriority());
        System.out.println("Priority of the thread th2 is : " + th2.getPriority());
        System.out.println("Priority of the thread th3 is : " + th3.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 th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

When it comes to thread execution, we know that a thread with a high priority will take precedence over a thread with a lower priority. However, there may be other situations in which two threads have the same priority. The Java thread scheduler handles all of the processing for thread management. Consider the following example to see what happens if two threads have the same priority.

import java.lang.*;
public class ThreadPriorityExample1 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());

        ThreadPriorityExample1 th1 = new ThreadPriorityExample1();
        System.out.println("Priority of the thread th1 is : " + th1.getPriority());
    }
}

Output:

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

Explanation: If two threads have the same priority, it is impossible to predict which thread will be executed first. The execution is then determined by the thread scheduler’s algorithm (First Come, First Serve, Round-Robin, and so on).

Implementation of IllegalArgumentException in Java

We know that if the value of the method getPriority()’s parameter newPriority is not in the range (1 to 10), we get the IllegalArgumentException. Let us examine this with the help of an example.

import java.lang.*;
public class IllegalArgumentException extends Thread {
    public static void main(String argvs[]) {
        Thread.currentThread().setPriority(17);
        System.out.println(Thread.currentThread().getPriority());
    }
}

Output

Exception in thread "main" java.lang.IllegalArgumentException
    at java.base/java.lang.Thread.setPriority(Thread.java:1141)
    at IllegalArgumentException.main(IllegalArgumentException.java:12)

Impact of Thread Priorities

Thread priorities influence how the JVM schedules and allocates resources to threads. A higher priority thread has a better chance of being executed before lower priority threads. However, it’s important to remember that priority alone does not determine the order of thread execution. The JVM’s thread scheduler takes other factors, such as the underlying operating system and thread states, into account.

Thread priority is useful when certain threads require more processing time or have critical tasks. By giving such threads a higher priority, developers can ensure that they receive enough CPU time to complete their tasks on time. It is not, however, recommended to rely solely on thread priorities to achieve specific execution behavior.

Best Practices and Considerations for Thread Priority in Java

When working with thread priorities in Java, it’s essential to keep the following considerations in mind:

  • Thread priorities are relative: Thread priorities are relative to each other and not absolute. The relationship between priorities is what matters, rather than the specific values assigned.

  • Platform dependency: Thread scheduling behavior can vary across different JVM implementations and operating systems. Therefore, it’s crucial to avoid making assumptions about the precise behavior of thread priorities.

  • Avoid excessive priority use: Overusing thread priorities or assigning extreme values to them may lead to unexpected and non-portable behavior. It is generally advisable to use priorities sparingly and focus on designing efficient algorithms and proper thread synchronization.

  • Design robust and responsive applications: Prioritizing threads alone does not guarantee responsive and well-performing applications. It is important to design applications carefully, taking into account proper thread synchronization, efficient resource utilization, and algorithm optimization.

Conclusion
Thread priorities in Java multithreaded applications allow you to control the order of thread execution and resource allocation. Developers can fine-tune the behavior of their applications to some extent by appropriately setting thread priorities. However, it is critical to use thread priorities wisely and to understand their platform-dependence. Finally, developing well-designed, efficient, and responsive applications necessitates a comprehensive approach that includes proper synchronization, algorithm optimization, and thread management techniques.

Frequently Asked Questions (FAQs)

Here are some of the most frequently asked questions on thread priority in Java

Q1. What is thread priority in Java?
Thread priority in Java is a feature that allows you to assign a priority level to a thread. It is represented by an integer value ranging from 1 to 10, where 1 is the lowest priority and 10 is the highest priority. The thread scheduler uses these priorities as hints to determine the order in which threads should be scheduled for execution.

Q2. What are the three thread priorities in Java?
In Java, there are three predefined thread priorities available as constants in the Thread class:
Thread.MIN_PRIORITY (1): Represents the minimum priority value that can be assigned to a thread.
Thread.NORM_PRIORITY (5): Represents the default priority value assigned to a thread if no specific priority is set.
Thread.MAX_PRIORITY (10): Represents the maximum priority value that can be assigned to a thread.

Q3. How do I check thread priority?
You can check the priority of a thread in Java using the getPriority() method provided by the Thread class. Here’s an example:

Thread thread = Thread.currentThread();
int priority = thread.getPriority();
System.out.println("Thread priority: " + priority);

This code retrieves the priority of the current thread using Thread.currentThread() and then prints it to the console.

Q4. What are the categories of thread priority?
In Java, there are two broad categories of thread priority:
User Threads: These are threads created by the application and are under the control of the programmer. The priorities of user threads can be set and adjusted as needed.
System Threads: These threads are managed by the JVM and the underlying operating system. They handle various system-level tasks and typically have higher priorities to ensure their timely execution. The priorities of system threads are generally not intended to be modified by application developers.

Leave a Reply

Your email address will not be published. Required fields are marked *