Java-Thread Priority

Thread Priority

We can assign different priorities to the threads defined in a program by using the setPriority( ) method. When we invoke this method, we have to pass a priority parameter to it. The priority parameter always takes a value between 0 and 10. One of the three static constants in the Thread class, namely the MAX_PRIORITY, MIN_PRIORITY and NORM_PRIORITY, is used to set the priority of a thread.

The value 0 of the priority parameter is denoted by MIN_PRIORITY, which is a predefined static constant in the Thread class. Similarly, the value 10 of the priority parameter is denoted by MAX_PRIORITY, which is also a predefined static constant in the Thread class. The value 5 of the priority parameter is denoted by NORM_PRIORITY, which is also a predefined constant in the Thread class. The default priority of a Java thread is NORM_PRIORITY.

Whenever the thread scheduler needs to take a decision regarding which thread to run next, it picks the thread with the highest priority. If there are many threads with the same high priority in the queue, the scheduler chooses one of them for execution. If a higher priority thread wakes up after sleeping for some time while a lower priority thread is running, the scheduler will run the higher priority thread and suspend the current lower priority thread. The following program illustrates the usage of the priority concept.

Program

aaa

Program Source

class NewThread extends Thread{

    public long count;
    
    NewThread(int priority)
    {
        setPriority(priority);
        start();
    }

    public void run()
    {
        for(;;)
        {
            count++;        
        }
    }
}

public class Javaapp {

    public static void main(String[] args) {
    
        NewThread th1 = new NewThread(Thread.MIN_PRIORITY);
        NewThread th2 = new NewThread(Thread.NORM_PRIORITY);
        NewThread th3 = new NewThread(Thread.MAX_PRIORITY);
        try{
            Thread.sleep(3000);
        }catch(InterruptedException ie)
        {
            System.out.println("Main Thread Interrupted");
        }
        th1.stop();
        th2.stop();
        th3.stop();
        System.out.println("Thread th1.count = "+th1.count);
        System.out.println("Thread th2.count = "+th2.count);
        System.out.println("Thread th3.count = "+th3.count);
    }
}

Leave a Comment