Saturday, 25 January 2014

THREAD PRIORITIES

SET THREAD PRIORITY IN JAVA

Explain thread priority in java with suitable example

In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads. Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.  Priorities are integer values from 1 to 1.

               Constant                                     Description

    Thread.MIN_PRIORITY             The maximum priority of any thread (an int value of 10)
    Thread.MAX_PRIORITY           The minimum priority of any thread (an int value of 1)
    Thread.NORM_PRIORITY        The normal priority of any thread (an int value of 5)

The methods that are used to set the priority of thread shown as:
  
           Method                                          Description

        setPriority()                            This is method is used to set the priority of thread.  
        getPriority()                            This method is used to get the priority of thread.

Example:

class MyThread1 extends Thread{
  MyThread1(String s){
  super(s);
  start();
  }
  public void run(){
  for(int i=0;i<3;i++){
  Thread cur=Thread.currentThread();
  cur.setPriority(Thread.MIN_PRIORITY);
  int p=cur.getPriority();
  System.out.println("Thread Name  :"+Thread.currentThread().getName());
  System.out.println("Thread Priority  :"+cur);
  }
  }
}
  class MyThread2 extends Thread{
  MyThread2(String s){
  super(s);
  start();
  }
public void run(){
  for(int i=0;i<3;i++){
  Thread cur=Thread.currentThread();
  cur.setPriority(Thread.MAX_PRIORITY);
  int p=cur.getPriority();
  System.out.println("Thread Name  :"+Thread.currentThread().getName());
  System.out.println("Thread Priority  :"+cur);
  }
  }
}
public class ThreadPriority{
  public static void main(String args[]){  
  MyThread1 m1=new MyThread1("My Thread 1");
  MyThread2 m2=new MyThread2("My Thread 2");
  }
}


Output:

Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Priority :Thread[My Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,1,main]








































Example:

No comments:

Post a Comment