freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Thread Priorities

1. Every Thread in java has some property. It may be default priority provided be the JVM or customized priority provided by the programmer.
2. The valid range of thread priorities is 1 – 10. Where one is lowest priority and 10 is highest priority.
3. The default priority of main thread is 5. The priority of child thread is inherited from the parent.
4. Thread defines the following constants to represent some standard priorities.
5. Thread Scheduler will use priorities while allocating processor the thread which is having highest priority will get chance first and the thread which is having low priority.
6. If two threads having the same priority then we can’t expect exact execution order it depends upon Thread Scheduler.
7. The thread which is having low priority has to wait until completion of high priority threads.
8. Three constant values for the thread priority.
       a. MIN_PRIORITY = 1
       b. NORM_PRIORITY = 5
       c. MAX_PRIORITY = 10
Thread class defines the following methods to get and set priority of a Thread.
    a. Public final int getPriority()
    b. Public final void setPriority(int priority)
Here ‘priority’ indicates a number which is in the allowed range of 1 – 10. Otherwise we will get
Runtime exception saying “IllegalArgumentException”.

Thread Priorities program

import java.util.*;
class frist extends Thread
{
public void run()
{
System.out.println(" frist thread stated");
for (int i=0;i<10 ;i++ )
{
System.out.println(i);
}
System.out.println("frist thread ended");
}
};
class secound extends Thread
{
public void run()
{
System.out.println("Secound thread ");
for (int i=0;i<10 ;i++ )
{
System.out.println(i);
}
System.out.println("Secound thread ended");
}
};
class threed extends Thread
{
public void run()
{
System.out.println("3th thread");
for (int i=0;i<10 ;i++ )
{
System.out.println(i);
}
System.out.println("3th thread ended");
}
};
class Test
{
public static void main(String[] durga)
{
frist thread1=new frist();
secound thread2=new secound();
threed thread3=new threed();
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread3.setPriority(thread2.getPriority()+1);
System.out.println("frist Thread");
thread1.start();
System.out.println("secound Thread");
thread2.start();
System.out.println("3th Thread");
thread3.start();
}
};

intput and output

output:frist Thread
secound Thread
3th Thread
Secound thread
0
1
2
3
4
5
6
7
8
9
Secound thread ended
frist thread stated
0
1
2
3
4
5
6
7
8
9
frist thread ended
3th thread
0
1
2
3
4
5
6
7
8
9
3th thread ended