Monday, September 16, 2013

How to Set Priority of Thread - Thread Priority Example in Java

Each Thread has priority. Thread Scheduler schedules thread based on thread priority. You can set priority of thread. It's important to understand Preemptive Scheduling and Time Slicing before moving ahead.

Priorities are integer values from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY).
Default Priority is Thread.NORM_PRIORITY (Value 5)



If You observe Thread.class available in java.lang package in Java It has following static variables defined for Thread Priority.
/**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

Thread Priority Example in Java :
package com.anuj.threading;

/**
 * Thread Priority Example
 * @author Anuj
 *
 */
class ThreadPriorityExample extends Thread{

 @Override
 public void run() {
  String threadName = Thread.currentThread().getName();
  System.out.println("Running Thread is : "+ threadName + " Priority: "+Thread.currentThread().getPriority());  
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  ThreadPriorityExample t1 = new ThreadPriorityExample();
  ThreadPriorityExample t2 = new ThreadPriorityExample();
  ThreadPriorityExample t3 = new ThreadPriorityExample();
  
  t1.setPriority(MIN_PRIORITY);
  t2.setPriority(MAX_PRIORITY);
  t3.setPriority(NORM_PRIORITY);
  
  t1.start();
  t2.start();
  t3.start();
 }

}

Output :
Running Thread is : Thread-0 Priority: 1
Running Thread is : Thread-1 Priority: 10
Running Thread is : Thread-2 Priority: 5

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/