In java, when two or more than two thread is computing for CPU time, every thread is assigned a priority value. A highest Priority thread get preference over lower priority thread.
All Java threads have a priority in the range 1-10.
Top priority is 10, lowest priority is 1.Normal priority ie. priority by default is 5.
Thread.MIN_PRIORITY – 1 minimum thread priority
Thread.MAX_PRIORITY – 10 maximum thread priority
Thread.NORM_PRIORITY – 5 maximum thread priority
Whenever a new Java thread is created it has the same priority as the thread which created it.
Thread priority can be changed by the setPriority() method.
Example: Write a program to demonstrate the thread priority.
class ThreadPriority extends Thread {
public void run(){
for(int i=1;i<=5;i++){
try{
System.out.println("Thread "+Thread.currentThread().getName()+
" priority "+Thread.currentThread().getPriority());
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("InterruptedException "+e.getMessage());
}
}
}
}
public class ThreadPriorityMain{
public static void main(String s[]){
ThreadPriority t1=new ThreadPriority();
ThreadPriority t2=new ThreadPriority();
ThreadPriority t3=new ThreadPriority();
t1.setName("Thread 1");
t2.setName("Thread 2");
t3.setName("Thread 3");
t2.setPriority(6);
t3.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start ();
}
}
Thread Thread 3 priority 10 Thread Thread 1 priority 5 Thread Thread 2 priority 6 Thread Thread 3 priority 10 Thread Thread 2 priority 6 Thread Thread 1 priority 5 Thread Thread 3 priority 10 Thread Thread 2 priority 6 Thread Thread 1 priority 5 Thread Thread 3 priority 10 Thread Thread 2 priority 6 Thread Thread 1 priority 5 Thread Thread 3 priority 10 Thread Thread 2 priority 6 Thread Thread 1 priority 5