Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.
public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).
A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU. A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. Whenever a higher priority thread wants to run it does.
Thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.
Ex:
import
java.lang.*;
public class ThreadPriorityExample1 extends Thread
{
public void run()
{
System.out.println("Inside
the run() method");
}
public static void main(String argvs[])
{
Thread.currentThread().setPriority(7);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
ThreadPriorityExample1 th1 = new ThreadPriorityExample1();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
}
}
No comments:
Post a Comment