>

Saturday, December 15, 2012

Thread Part IV - Determine Thread Priority in Java

Thread Part IV
Thread Priority

Thread Priority is set which thread to be priority to execute first, in theory the thread with the higher priority will be get more time CPU then the lower priority thread, the value of priority is MIN_PRIORITY to MAX_PRIORITY is 1 to 10 and for normal priority NORM_PRIORITY is 5. for determine priority in thread we use method setPriority() and to get the value priority we use method getPriority() both are belong to thread class. Ok let’s try how both method work, the idea was to figure how many looping created for high priority and low priority. First we created generated thread as shown bellow,

public class MyThreadPriority implements Runnable{

  private Thread thread;
  private long n;

  private boolean finish = false;

  MyThreadPriority(String name, int priority){
   thread = new Thread(this, name);
   thread.setPriority(priority);
  }

  @Override
  public void run() {
    while (!finish) {
     n++;
    }
  }

 public void start(){
  thread.start();
 }

 public void stop(){
  finish = true;
 }

 public long getN(){
  return n;
  }

 public Thread getThread(){
   return thread;
 }
}

 

then we try to create demonstration to check how priority work

public class PriorityThreadDemo {

public static void main(String[]args)throws InterruptedException{

  MyThreadPriority t1= new MyThreadPriority("high"
  Thread.NORM_PRIORITY+ 2);

  MyThreadPriority t2 = new MyThreadPriority("low"
  Thread.NORM_PRIORITY-2);

  t1.start();
  t2.start();

  Thread.sleep(5000);

  t1.stop();
  t2.stop();

  t1.getThread().join();
  t2.getThread().join();

  System.out.println("The number of looping for "+
  t1.getThread().getName()+" thread priority" +" : "+ t1.getN());

  System.out.println("The number of looping for "+
  t2.getThread().getName()+" thread priority" +" : "+ t2.getN());


  }
}

if we run the class above the console will show look like bellow,

The number of looping for high thread priority : 1351468823
The number of looping for low thread priority : 1301962925

from the result above the higher priority thread will do many looping than the lower one, and the value of looping above will be different for every CPU speed and how many applications running, but all will show the higher priority will do many looping than the lower one.

No comments:

Post a Comment