Friday 11 November 2016

Thread Priority



    In Java, each thread can be assigned a priority, which affects the order in which it is scheduled for running.
      The priority of a thread can be set using the setPriority() method as:
Threadname.setPriority(intNumber);
   The intNumber is an integer value to which the thread’s priority is set. Thread class defines several priority constants:
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
    The default priority of a thread is NORM_PRIORITY.
    If a higher priority thread arrives, then the currently running thread will be preempted by the incoming thread thus forcing the current thread to move to the Runnable state.
    Example:
class A extends Thread
{
public void run()
 {
for(int i=1;i<=3;i++)
System.out.println("Thread A is executing");
 }
}
class B extends Thread
{
public void run()
 {
for(int j=1;j<=3;j++)
System.out.println("Thread B is executing");
 }
}
class C extends Thread
{
public void run()
 {
for(int k=1;k<=3;k++)
System.out.println("Thread C is executing");
 }
}
classThreadpriority
{
public static void main(String args[])
 {
  A a= new A();
  B b=new B();
  C c=new C();
a.setPriority(Thread.MIN_PRIORITY);
a.start();
b.setPriority(a.getPriority()+1);
c.setPriority(Thread.MAX_PRIORITY);
b.start();
c.start();
 }
}
Output:
Thread C is executing
Thread C is executing
Thread C is executing
Thread B is executing
Thread A is executing
Thread B is executing
Thread B is executing
Thread A is executing
Thread A is executing

No comments:
Write comments