Thread priority in java

A thread is a part or entity of a process that is scheduled for execution. As we know java is a multithreading language which means JVM allow an application to have multiple thread running concurrently.

Thread priority in java

A thread is a part or entity of a process that is scheduled for execution. As we know java is a multithreading language which means JVM allow an application to have multiple thread running concurrently.

thread priority in java

Thread priority in java

A thread is a part or entity of a  process that  is scheduled for execution. As we know java is a multithreading language which means JVM allow an application to have multiple thread running concurrently. In java each and every thread has priority , priority means which decides the order of execution of that thread . Thread with higher priority will run first with thread with lower priority, and thread with equal priority will be treated same by scheduler and they will follow FCFS(First Cum First Serve) algorithm. We can also set the priority of thread by using setPriority() method as follows:

ThreadNamesetPriority(int number);

Here number is an integer value between 1 to 10, here 1 is minimum priority and 10 is maximum priority.

Thread class defines some priority constant as follows:

MIN_PRIORITY = 1

NORM_PRIORITY = 5

MAX_PRIORITY = 10;

In any thread NORM_PRIORITY is default one.

Example : A program how to set or get priority of thread in java.

class A extends Thread
{
	public void run()
	{
		 System.out.println("Thread A strated");
                                     for(int i=0;i<=5;i++)
		{
			System.out.println("For thread A = "+i);
		}
	  System.out.println("Exit from Thread A");
	}
	
}

 class B extends Thread
{
	public void run()
	{
		System.out.println("Thread B strated");
                                     for(int i=0;i<=5;i++)
		{
			System.out.println("For thread B = "+i);
		}
	  System.out.println("Exit from Thread B");
	}
	
}

public class ThreadPriority 
    {   
    public static void main(String args[])
    {
    	A th1=new A();
    	B th2=new B();
    	th1.setPriority(Thread.NORM_PRIORITY);
    	th2.setPriority(th1.getPriority()+3);
    	System.out.println("Start thread A");
    	th1.start();
     
    	System.out.println("Start Thread B");
    	th2.start();
                   System.out.println("End of Main Thread");
    	 }   
    }

In the above program what we have done is creating two class A and B and one main class in which creating object of both class. By setPriority() method set the priority to normal priority of thread  A that is 5, and  getting the priority of thread B and adding 3 to it so, thread B will execute first after completing only thread A get chance to execute.

Output: After compiling and executing the above program.

Download SourceCode