1. Every Thread in java having some priority.
  2. The range of valid thread priorities is (1-10) (1 is least & 10 is Highest).
  3. Thread class defines the following constant for representing some standard priorities.
    • Thread.MIN_PRIORITY(1)
    • Thread.NORM_PRIORITY(5)
    • Thread.MAX_PRIORITY(10)
  4. Thread scheduler use these priorities while allocating C.P.U.
  5. The Thread which is having highest priority will get chance first for execution.
  6. If two threads having the same priority then which thread will get chance first for execution is decided by Thread Scheduler, which is vendor dependent i.e we can’t expect exactly.
  7. The default priority for the main thread is 5, but for all the remaining threads the priority will be inherit from parent i.e what ever the parent has the same priority the child thread also will get.
  8. Thread class contains the following methods to set and get priorities of thread.
    • public final void setPriority(int priority)
      Where priority should be from 1-10, other wise we will get RuntimeException saying IllegalArgumentException.
    • public final int getPriority();

Example:

class TestThread extends Thread{
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Child Thread");
        }
    }
}

public class ThreadDemo {
 
    public static void main(String[] args) {
         
        TestThread testThread = new TestThread();
        System.out.println(testThread.getPriority());
        testThread.setPriority(10);//------(1)
        testThread.start();
        for (int i = 1; i <= 5; i++) {
            System.out.println("Main Thread");
        }
    }
}

Note:

  1. If we are not commenting line 1, then child thread priority is 10, and main thread priority is 5,hence child thread will get chance first and after completing child thread only main thread will get chance .Hence the output of the above program is
    Child Thread
    Child Thread
    Child Thread
    ....
    ....
    Main Thread
    Main Thread
    Main Thread
    ....
    ....
    
  2. If we are commenting line 1, then both main and child threads have the same priority 5.Which thread will get chance first we can’t expect exactly it is vendor dependent.
  3. Some Operating Systems may not provide support for thread priorities.