Java Thread Priorities


 

Java Thread Priorities

In this section, we will discuss how to set thread priorities with example.

In this section, we will discuss how to set thread priorities with example.

Java Thread Priorities

In this section, we will discuss how to set thread priorities with example.

Thread Priorities:

Thread priority is set in form of integer, which is handled by the thread scheduler. Thread starts running according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.

Thread having higher priority, execute first. Java priorities ranges from MAX_PRIORITY (constant value 10) to
MIN_PRIORITY (constant value 1).

Thread class provides you 3 priority -

  • MAX_PRIORITY : It is maximum priority that a thread hold. Its constant value is 10.
  • MIN_PRIORITY : It is minimum priority that a thread hold. Its constant value is 1.
  • NORM_PRIORITY : It is default priority that a thread hold. Its constant value is 5.

Java thread provides method to set and to get priority. These methods are - setPriority, getPriority

setPriority(int newPriority) : This method sets new priority to the thread. It throws IllegalArgumentException and SecurityException exception.

int getPriority() : It returns the priority of specified thread. Its return type is int.

Example :In this example we are using thread priority methods to get and set priority. default priority value is 5. so when we call thread.getPriority(), It returns 5. Next we are setting MAX_PRIORITY. now the thread.getPriority() returns value 10.

public class ThreadPriority implements Runnable {

    Thread thread;

    public ThreadPriority() {
    	thread = new Thread(this);
    	thread.start();
    }

    public void run() {
        /* getting Priority of the thread*/
        System.out.println( " Priority of "+thread.getName()+" is "+thread.getPriority());
        
        /* setting Priority of the thread*/
        thread.setPriority(Thread.MAX_PRIORITY);
        
        /* getting Priority of the thread*/
        System.out.println(" New Priority of "+thread.getName()+" is "+thread.getPriority());
    }

    public static void main(String[] args) {
        new ThreadPriority();
    }
}

Output :

 Priority of Thread-0 is 5
 New Priority of Thread-0 is 10

Ads