Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. In theory, higher-priority threads get more CPU time than lower-priority threads. In practice, the amount of CPU time that a thread gets often depends on several factors besides its priority. (For example, how an operating system implements multitasking can affect the relative availability of CPU time.) A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower-priority thread.

Java permits us to set the priority of a thread using the setPriority() method as follows:

                       ThreadName.setPriority (intNumber)

The intNumber is an integer value to which the thread’s priority is set. The Thread class defines several priority constants:

MIN_PRIORITY      =      1

NORM_PRIORITY =     5

MAX_PRIORITY     =     10

The intNumber may assume one of these constants or any value between 1 and 10. Note that the default setting is NORM_PRIORITY.

//Program to demonstrate thread priority.

class ThreadA extends Thread{

public void run() {

for(int i=1;i<=5;i++) {

System.out.println("Running thread "+i+" From Class A");

}

System.out.println("Exit from Class A");

}

}

 

class ThreadB extends Thread{

public void run() {

for(int j=1;j<=5;j++) {

System.out.println("Running thread "+j+" From Class B");

}

System.out.println("Exit from Class B");

}

}

class ThreadC extends Thread{

public void run() {

for(int k=1;k<=5;k++) {

System.out.println("Running thread "+k+" From Class C");

}

System.out.println("Exit from Class C");

}

}

public class ThreadExample {

public static void main(String[] args) {

ThreadA t1=new ThreadA();

ThreadB t2=new ThreadB();

ThreadC t3=new ThreadC();

t1.setPriority(Thread.MIN_PRIORITY);

t2.setPriority(t1.getPriority()+1);

//or t2.getPriority(2) t3.setPriority(Thread.MAX_PRIORITY);

t1.start();

t2.start();

t3.start();

}

}

Note that although the threadA started first, the higher priority threadB has preempted it and started printing the output first. Immediately, the threadC that has been assigned the highest priority takes control over the other two threads. The threadA is the last to complete.