Java program to set priorities of thread

Q. Write a program to set the priorities of the thread.

Answer:

Thread priorities:
In Java, each thread has a priority. Priorities are represented by number from 0 to 10. The default priority of NORM_PRIORITY is 5, MIN_PRIORITY is 1 and MAX_PRIORITY is 10.

In this example, we calculate the priority of each thread. The setPriority() method is used to set the priority of the thread.

ThreadPriority.java

public class ThreadPriority extends Thread
{
      public void run()
      {
            System.out.println("run() method");
            String threadName = Thread.currentThread().getName();
            Integer threadPrio = Thread.currentThread().getPriority();
            System.out.println(threadName + " has priority " + threadPrio);
      }
      public static void main(String[] args) throws InterruptedException
      {
            ThreadPriority t1 = new ThreadPriority();
            ThreadPriority t2 = new ThreadPriority();
            ThreadPriority t3 = new ThreadPriority();

            t1.setPriority(Thread.MAX_PRIORITY);
            t2.setPriority(Thread.MIN_PRIORITY);
            t3.setPriority(Thread.NORM_PRIORITY);
  
            t1.start();
            t2.start();
            t3.start();
      }
}


Output:

thread priorities