Java Thread Priority

Introduction

In Java, every thread has a priority.

Higher priority threads get more preference in terms of CPU, I/O time, etc. than lower priority threads.

Higher priority threads should ideally receive more importance than lower priority ones.

Priorities are represented by integer numbers from 1 (lowest) to 10 (highest).

They are represented by two static final fields MIN_PRIORITY and MAX_PRIORITY of Thread class respectively.

A new thread receives its initial priority equal to the priority of its creator thread.

The JVM assigns a priority value equal to the final field NORM_PRIORITY to the main thread.

Java defines these fields as follows:

public final static int MIN_PRIORITY = 1; 
public final static int NORM_PRIORITY = 5; 
public final static int MAX_PRIORITY = 10; 

The following program prints their values:

public class Main { 
  public static void main(String args[]) { 
     System.out.println("Lowest thread priority: "+Thread.MIN_PRIORITY); 
     System.out.println("Normal thread priority: "+Thread.NORM_PRIORITY); 
     System.out.println("Highest thread priority: "+Thread.MAX_PRIORITY); 
   } // w ww.j av  a 2s  .  c o m
} 

The following methods are available to work with priority:


public final int getPriority() 
public final void setPriority(int newPriority) 

The following program demonstrates their usage:

public class Main extends Thread {
  public void run() {
    System.out.println("Child's initial priority: " + getPriority());
    setPriority(3);/*from w  ww . jav  a 2  s .c  o  m*/
    System.out.println("After change, child's priority: " + getPriority());
  }

  public static void main(String args[]) {
    Thread t = Thread.currentThread();
    System.out.println("Main's initial priority: " + t.getPriority());
    t.setPriority(7);
    System.out.println("After change, main's priority: " + t.getPriority());
    new Main().start();
  }
}

The following program demonstrates how two threads with different priorities are handled.

class MyThread extends Thread {
  int count = 0;/*from   w  w w .  j a  v a2 s.  c o  m*/

  public int getCount() {
    return count;
  }

  public void run() {
    while (true)
      count++;
  }
}

public class Main {
  public static void main(String args[]) throws InterruptedException {
    MyThread t1 = new MyThread();
    MyThread t2 = new MyThread();
    t1.setPriority(Thread.MAX_PRIORITY);
    t2.setPriority(Thread.MIN_PRIORITY);
    t1.start();
    t2.start();
    Thread.sleep(100);
    System.out.println("Thread 1 count: " + t1.getCount());
    System.out.println("Thread 2 count: " + t2.getCount());
  }
}



PreviousNext

Related