Thread Priorities

Thread Priorities

Every Thread in java having some priority. The range of valid thread priorities is (1-10) (1 is least & 10 is Highest). Thread class defines the following constant for representing some standard priorities.

Thread.MIN_PRIORITY  -> 1
Thread.NORM_PRIORITY -> 5
Thread.MAX_PRIORITY  -> 10

Thread scheduler use these priorities while allocating C.P.U. The Thread which is having highest priority will get chance first for execution. 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.

The default priority for the main thread only the 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.

Thread class contains the following methods to set and get priorities of thread.

1. public final void setPriority(int priority);

Where priority should be from 1-10 other wise R.E: IllegalArgumentException.

2. public final int getPriority();

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

public class MyThreadPriority {
   public static void main(String arg[]) {
      MyThread t = new MyThread();
      System.out.println(t.getPriority());
      t.setPriority(10);
      t.start();
      for (int i = 0; i < 5; i++) {
         System.out.println("Main Thread");
      }
   }
}
Output
5
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Thread Priorities
Scroll to top