Thread priority

Thread priorities are integer values between 1 and 10 used by the thread scheduler to assign the CPU time for the thread for execute their task. When many threads are executed by the thread scheduler, then the thread scheduler uses the priority associated with thread to decide that how much CPU time should be assigned for particular thread. The thread having the higher priority will execute fast then lower priority because the CPU time assigned to higher priority thread is more then lower priority thread.


Some constants are defined in the thread class for specify the priority values and they can be used to assign the relative priorities among the threads. Those are below with their access specifier and access modifier.

public static final int
MAX_PRIORITY
10
public static final int
MIN_PRIORITY
1
public static final int
NORM_PRIORITY
5

The execution of multiple threads on a single CPU, in some order, is called scheduling. The Java platform supports a simple, deterministic scheduling algorithm called fixed-priority scheduling.

there are following methods those are used to handle the thread priority.
getPriority()
It returns the integer type value which represents the priority associated with thread.
setPriority(int newPriority)
It changes the priority of the thread. The new priority is passed as the integer type argument.

//Thread priority
class MyThread extends Thread
{    int i;
    String msg;
    MyThread(String msg)
    {
        this.msg=msg;
    }
    public void run()
    {    
        while(true)
        {    
            i++;
        }
    }
}
class MyThr
{
    public static void main(String ar[])
    {
        System.out.println("Start main");
        MyThread t1=new MyThread("this is t1 ");
        MyThread t2=new MyThread("this is t2 ");
        t1.setDaemon(true);
        t2.setDaemon(true);
        t1.setPriority(5);   
        t2.setPriority(7);
        t1.start();
        t2.start();   
        try{
            Thread.sleep(500);
        }catch(InterruptedException e){}
        System.out.println("t1 "+t1.i);
        System.out.println("t2 "+t2.i);
        System.out.println("Exit from main");
    }
}
/OUTPUT
 Start main
t1 60239458
t2 1324496589
Exit from main
*/

No comments:

Popular Posts