Java Thread Priority

  • We know that in java each thread have a priority that I had discussed from the beginning.
  • Priority is nothing but an integer value ranging from 1 to 10.
  • Minimum priority of a thread is 1, maximum priority of a thread is 10, and default priority is 5 which is also called normal priority.
  • Threads having same priority are treated equally by the java scheduler, therefore they share the processor on FCFS(First-Come First-Serve) basis.
  • We set a priority of a thread by using setPriority( ) method, that is
    Threadname.setPriority(intNumber) ;
    Where intNumber is an integer value between 1 to 10.
  • The Thread class defines the different constants such as
    MIN_PRIORITY = 1
    NORM_PRIORITY = 5
    MAX_PRIORITY = 10
  • When multiple tasks are assigned to multiple threads with different priorities, then the higher priority of thread will be given more JVM time and hence it will complete the task earlier than the thread with lower priority.

Let's see a program for use of thread priorities :

class A extends Thread
{
public void run( )
{
int p;
for(p=1;p<=5;p++)
{
System.out.println("p="+p);
}
}
}
class B extends Thread
{
public void run( )
{
int q;
for(q=1;q<=5;q++)
{
System.out.println("q="+q);
}
}
}
class C extends Thread
{
public void run( )
{
int r;
for(r=1;r<=5;r++)
{
System.out.println("r="+r);
}
}
}
class Gyana
{
public static void main(String args[ ])
{
A t1=new A( );
B t2=new B( );
C t3=new C( );
t3.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(2);
t1.setPriority(Thread.MIN_PRIORITY);
t1.start( );
t2.start( );
t3.start( );
}
}

Output

r=1
r=2
r=3
r=4
r=5
p=1
p=2
p=3
p=4
p=5
q=1
q=2
q=3
q=4
q=5

In this program the output represents the effect of assigning higher priority to a thread. Although thread A started first, but due to higher priority of thread B, B have preempted it and started printing the output first. At the same time, thread C that have assigned highest priority takes control over the other two threads. The thread A is the last to execute.

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

Silansoftware Pvt.Ltd, BBSR
Call to: 0674-2361252

Comment