/* related posts with thumb nails */

Thread Priorities:

In Java, each thread is assigned a priority, which affects the order in which it is scheduled for running. The threads of the same priority are given equal treatment by the Java scheduler and, therefore, they share the processor on a first-come, first-serve basis. Java permits us to set the priority of a thread using the setPriority() method as follows:
ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the thread's priority is set. The Thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10

The default setting is NORM_PRIORITY. Most user-level processes should use NORM_PRIORITY, plus or minus 1. Back-ground tasks such as network I/O and screen repainting should use a value very near to the lower limit. We should be very cautious when trying to use very high priority values. By assigning priorities to threads, we can ensure that they are given the attention they deserve. Whenever multiple threads are ready for execution, the Java system chooses the highest priority thread and executes it. 

The following program illustrates the use of thread priorities, with the output; one can clearly understand that the threads with higher priorities will be executed faster.
class MyThread extends Thread
{  
   String s;
   MyThread(String ss,int p)
   {
     setPriority(p);
     s=ss;
     start();
   }
   public void run()
   {
      for(int i=1;i<=3;i++)
      {
        System.out.println(s+i);
           try   {  Thread.sleep(1000);  }  catch(Exception e) { }
      }
   }
}
class Test
{
   public static void main(String as[])
   {
     MyThread t1=new MyThread("Alpha",Thread.NORM_PRIORITY);
     MyThread t2=new MyThread("Beta",Thread.MIN_PRIORITY);
     MyThread t3=new MyThread("Gamma",Thread.MAX_PRIORITY);
   }
}
The above program generates the following output:
Alpha1
Beta1
Gamma1
Gamma2
Alpha2
Beta2
Gamma3
Alpha3
Beta3
Related Topics:

0 comments:

Post a Comment