0% found this document useful (0 votes)
75 views3 pages

Java Thread Priority Explained

Threads in Java have priorities between 1-10 that determine scheduling order, with higher priority threads running first. The Thread class defines constants for minimum (1), normal/default (5), and maximum (10) priorities. The getPriority() and setPriority() methods return and set a thread's priority respectively, within the valid range, and child threads inherit their parent's priority by default.

Uploaded by

MITALI SHARMA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views3 pages

Java Thread Priority Explained

Threads in Java have priorities between 1-10 that determine scheduling order, with higher priority threads running first. The Thread class defines constants for minimum (1), normal/default (5), and maximum (10) priorities. The getPriority() and setPriority() methods return and set a thread's priority respectively, within the valid range, and child threads inherit their parent's priority by default.

Uploaded by

MITALI SHARMA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Java Thread Priority in Multithreading

In a Multi threading environment, thread scheduler assigns processor to a thread based on priority of
thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either
be given by JVM while creating the thread or it can be given by programmer explicitly.
Accepted value of priority for a thread is in range of 1 to 10.

There are 3 static variables defined in Thread class for priority.

public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for this is 1.
public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly define it.
Value for this is 5.
public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.

Get and Set Thread Priority:

1. public final int getPriority(): [Link]() method returns priority of given


thread.
2. public final void setPriority(int newPriority): [Link]() method changes
the priority of thread to the value newPriority. This method throws IllegalArgumentException if
value of parameter newPriority goes beyond minimum(1) and maximum(10) limit.

Examples of getPriority() and setPriority()


import [Link].*;
  
class ThreadDemo extends Thread
{
    public void run()
    {
        [Link]("Inside run method");
    }
  
    public static void main(String[]args)
    {
        ThreadDemo t1 = new ThreadDemo();
        ThreadDemo t2 = new ThreadDemo();
        ThreadDemo t3 = new ThreadDemo();
  
        [Link]("t1 thread priority : " +
                              [Link]()); // Default 5
        [Link]("t2 thread priority : " +
                              [Link]()); // Default 5
        [Link]("t3 thread priority : " +
                              [Link]()); // Default 5
  
        [Link](2);
        [Link](5);
        [Link](8);
  
        // [Link](21); will throw IllegalArgumentException
        [Link]("t1 thread priority : " +
                              [Link]());  //2
        [Link]("t2 thread priority : " +
                              [Link]()); //5
        [Link]("t3 thread priority : " +
                              [Link]());//8
  
        // Main thread
        [Link]([Link]().getName());
        [Link]("Main thread priority : "
                       + [Link]().getPriority());
  
        // Main thread priority is set to 10
        [Link]().setPriority(10);
        [Link]("Main thread priority : "
                       + [Link]().getPriority());
    }
}

Output:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Main thread priority : 5
Main thread priority : 10
Note:

 Thread with highest priority will get execution chance prior to other threads. Suppose there are 3
threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2 will execute first based on maximum
priority 6 after that t1 will execute and then t3.

 Default priority for main thread is always 5, it can be changed later. Default priority for all other
threads depends on the priority of parent thread.
Example:

// Java program to demonstrat ethat a child thread


// gets same priority as parent
import [Link].*;
  
class ThreadDemo extends Thread
{
    public void run()
    {
        [Link]("Inside run method");
    }
  
    public static void main(String[]args)
    {
        // main thread priority is 6 now
        [Link]().setPriority(6);
  
        [Link]("main thread priority : " +
                   [Link]().getPriority());
  
        ThreadDemo t1 = new ThreadDemo();
  
        // t1 thread is child of main thread
        // so t1 thread will also have priority 6.
        [Link]("t1 thread priority : "
                                  + [Link]());
    }
}

Output:
Main thread priority : 6
t1 thread priority : 6

 If two threads have same priority then we can’t expect which thread will execute first. It
depends on thread scheduler’s algorithm(Round-Robin, First Come First Serve, etc)
 If we are using thread priority for thread scheduling then we should always keep in mind
that underlying platform should provide support for scheduling based on thread priority.
 Some OS won’t provide proper support for thread priority.

Common questions

Powered by AI

The primary benefit of using thread priorities in Java for scheduling is that it allows more critical tasks to execute before less critical ones, potentially improving application efficiency when managed correctly. Priorities can help balance workloads and optimize performance to ensure timely task completion. However, drawbacks include the risk of starvation, where lower-priority threads are indefinitely delayed, and priority inversion, where high-priority threads are blocked by lower-priority threads holding resources. Additionally, varying OS support for thread priorities can lead to inconsistent behavior across different platforms .

In Java, a child thread inherits the priority of the thread that creates it, unless explicitly set otherwise. For instance, if a main thread is running with a priority of 6, any child thread created by it will automatically inherit a priority of 6. This can be useful for maintaining a consistent execution order across related tasks within an application. For example, in a server application where main threads handle incoming requests, child threads could inherit priorities to ensure proper handling sequences matching request criticality .

If two Java threads have the same priority, the thread scheduler determines their execution order since Java does not guarantee the order in which threads of the same priority will operate. The execution order may vary based on the scheduling policy used by the operating system, such as Round-Robin or First Come First Serve. Therefore, without explicit OS support, the execution sequence cannot be predicted .

Assigning inappropriate priorities to threads in Java can lead to several problems such as starvation, where lower-priority threads are never executed because higher-priority threads continually preempt them. This can cause certain necessary tasks to be indefinitely delayed or neglected. Additionally, if priority inversion occurs, a low-priority thread could hold resources needed by a high-priority thread, leading to a deadlock situation if not properly managed with priority inheritance mechanisms. Incorrect priority assignment can also result in inefficient CPU usage and degrade application performance .

Thread priority in Java determines the order of execution in a multithreaded application. The thread scheduler assigns processor time to threads based on their priority; threads with higher priority are executed before those with lower priority. However, the correct functioning of thread priority depends on the underlying operating system's support for it. Java allows thread priority to be set between 1 (Thread.MIN_PRIORITY) and 10 (Thread.MAX_PRIORITY), with the default being 5 (Thread.NORM_PRIORITY). If an attempt is made to set a priority outside this range, an IllegalArgumentException is thrown .

Java ensures thread priorities remain within the specific range of 1 to 10 by utilizing the setPriority(int newPriority) method, which throws an IllegalArgumentException if an out-of-bounds priority is set. This restriction is crucial to prevent unrealistic or dangerous prioritization of threads, which could disrupt system stability and fairness in resource distribution. It maintains an environment where thread execution can be managed predictably and reliably .

Operating system support is crucial for thread priorities in Java because the Java Virtual Machine relies on the OS for thread scheduling. If the OS does not support thread priorities, the intended order of execution cannot be guaranteed. This may lead to threads executing in an unexpected order, particularly when multiple threads have the same priority. In the absence of OS support, thread scheduling may follow policies like Round-Robin or First Come First Serve, irrespective of the priorities set in Java code .

An IllegalArgumentException can occur if a priority outside the valid range of 1 to 10 is assigned to a thread in Java. The setPriority(int newPriority) method throws this exception to prevent assigning invalid priority levels, ensuring thread priority values remain within the accepted limits .

The default priority of a Java thread is determined by its parent thread. If no explicit priority is set, a thread inherits its parent's priority. For example, if the main thread has a priority of 6, a child thread created by it will also have a priority of 6 by default. The priority can be changed at any time using the setPriority(int newPriority) method, as long as the new priority adheres to the limits from 1 to 10 .

The main thread in a Java program has a default priority of 5 because it is set to Thread.NORM_PRIORITY, which is the standard baseline for thread priority. This default setting ensures a middle-ground priority that allows other threads explicitly set to higher or lower priorities to execute accordingly. Having a known default enables consistent priority management across platforms and simplifies initial program setup. Developers can adjust priorities later based on application needs .

You might also like