Turn Desktop View Off
by Dinesh Thakur Category: Multithreading

Every thread in Java has a priority that helps the thread scheduler to determine the order in which threads scheduled. The threads with higher priority will usually run before and more frequently than lower priority threads. By default, all the threads had the same priority, i.e., they regarded as being equally distinguished by the scheduler, when a thread created it inherits its priority from the thread that created it. However, you can explicitly set a thread's priority at any time after its creation by calling its setPriority() method. This method accepts an argument of type int that defines the new priority of the thread. Its syntax is.

final void setPriority(int priority)

Here, priority is an integer value that must range between 1 and 10, with 10 being the highest priority, 1 being the lowest and 5 being the default. If you specify a priority that is out of range, then an IllegalArgumentException exception thrown. Some thread priorities are static member variables of java.lang.Thread class. These include MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY representing values 1,5 and 10 respectively. The priority of the main thread is Thread.NORM_PRIORITY, i.e., 5. 

For example: To set the thread to the maximum priority, the following statements should be used.

Thread t1 = new thread(task);
t1.setPriority(Thread.Max_Priority);
t1.start() ;

You can also determine the current thread priority by calling the getPriority() method.

final int getpriority()

This method returns an in t value which indicates the current priority of the thread.

For example: To retrieve the current priority of the thread, use the following code.

System.out.println("Thread priority ="+t1.getpriority());
When the scheduler has to choose which of the Runnable threads is to run next, it always chooses the thread with the highest priority. If there is more than one thread with the highest priority, the scheduler runs each of them in a round robin fashion choosing the one which has been waiting longest to run. A low priority thread can run only when no higher priority threads are running. Also, the lower priority thread gain control if the higher priority thread is made to sleep using sleep() method or told to wait using the wait() method.

The Below Figure shows the thread priority scheduling. The arrow indicates the order of execution of threads.

Thread priority schduling
One should assign specific priority to a thread depending primarily upon the nature of the function performed by the thread. For example, A thread should be assigned low priority if it performs some kind of non-critical background task particularly one that takes a long time to complete. On the other hand, if a thread spends most of its time working for input and it performs a task that must complete quickly, then it should usually be assigned high priority.

Now let us consider the following program that illustrates how priority is assigned.

class X extends Thread

{
   public void run()
   {
     System.out.println("Thread x Started");
     for(int i=0; i<5; i++)
        {
              System.out.println("\t value of i in Thread x : " + i);
        }
              System.out.println("Threadx finished ");
    }
}
class Y extends Thread
{
      public void run()
    {
       System.out.println("Thread Y started");
       for(int i=0; i<5; i++)
           {
                 System.out.println("\tValue of i in Thread Y : " + i);
            }
                 System.out.println("ThreadY Finished");
      }
}
class Z extends Thread
{
      public void run()
    {
       System.out.println("Thread Z started");
       for(int i=0; i<5; i++)
           {
                 System.out.println("\tValue of i in Thread Z : " + i);
            }
                 System.out.println("ThreadZ Finished");
      }
}
 class ThreadPriority
{
         public static void main(String[] args)
      {
              System.out.println("Main thread started");
              X threadX = new X();
              Y threadY = new Y ();
              Z threadZ = new Z ();
              threadZ.setPriority(Thread.MAX_PRIORITY);  // priority = 10
              threadY.setPriority(threadX.getPriority()+1); // priority = 6
              threadX.setPriority(Thread.MIN_PRIORITY); // priority =l
              threadX.start(); threadY.start(); threadZ.start();
             try
             {
                 threadX.join();threadY.join();threadZ.join();
             }
                 catch(InterruptedException e){}
                 System.out.println("Main Thread Finished");
        }
}

Thread Priority in Java Example

Explaination: Although the threads are started in the order thread X followed by thread Y followed by thread Z but the thread Z (priority = 10) produces the output before thread Y (priority = 5) and thread X (priority = 1) because it has the highest priority.

NOTE: Generally higher priority threads can be expected to be given preference by the thread scheduler over lower priority threads. However, the implementation of thread schduling is left upto the JVM implementation.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles