Thread Priorities in java

Thread Priorities

Each thread have a priority. When the threads are created and started a ‘thread scheduler’ program in JVM will load them into memory and execute them. This scheduler will allot more JVM time to those threads which are having higher priorities. Priorities are represented by a number between 1 and 10. The minimum priority (shown by Thread.MIN_PRIORITY) of a thread is 1, and the maximum priority (Thread.MAX_PRIORITY) is 10. The normal priority of a thread (Thread.NORM_PRIORITY) is 5.

Example
class myclass extends Thread
{
int count=0; public void run()
{
for(int i=1;i<=10000;i++)
count++;
System.out.println(“Completed thread is:”+Thread.currentThread().getName());
System.out.println(“Thread priority is:”+Thread.currentThread().getPriority());
}
}
class test
{
public static void main(String args[])
{
myclass obj = new myclass();
Thread t1 = new Thread(obj,”one”);
Thread t2 = new Thread(obj,”two”);
t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);
t1.start();
t2.start();
}
}

Output:
Completed thread is:two
Thread priority is:5
Completed thread is:one
Thread priority is:2

Leave a Reply

Your email address will not be published. Required fields are marked *