Turn Desktop View Off
by Dinesh Thakur

Every thread in Java has a priority that helps the thread scheduler to determine the order in which threads are scheduled. The threads with higher priority will usually run before and/or more frequently than lower priority threads. By default, all the threads had the same priority i.e. they are regarded as being equally important by the scheduler, when a thread is 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 in t 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 will be 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.

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