Wednesday 5 March 2014

setMaxPriority : set priority to thread group

ThreadGroup class provides a method to set the Max priorities to all the threads in the group.

public final void setMaxPriority(int pri)
Sets the maximum priority of the group. Threads in the thread group that already have a higher priority are not affected. Threads that are going to add this group, after setting the priority to a group, have the maximum priority less than or equal to the group maximum priority. Setting the thread priority to more than the group maximum priority limits the thread priority to group maximum priority.

Example
class PriorityEx extends Thread{
 public void run(){
  try{
   Thread.currentThread().sleep(1000);
   Thread local = Thread.currentThread();
   System.out.println(local.getName() + " priority is " + local.getPriority());
  }
  catch(InterruptedException e){
  }
 }

 PriorityEx(ThreadGroup grp, String name){
  super(grp, name);
 }

 public static void main(String args[]){
  ThreadGroup group1 = new ThreadGroup("group1");

  PriorityEx t1 = new PriorityEx(group1, "Thread1");
  t1.setPriority(9);
  t1.start();

  group1.setMaxPriority(8);
  System.out.println("Group1 priority is set to " + group1.getMaxPriority());

  PriorityEx t2 = new PriorityEx(group1, "Thread2");
  t2.setPriority(9);
  t2.start();
 }
}
 

Output
Group1 priority is set to 8
Thread1 priority is 9
Thread2 priority is 8
   
Group1 maximum priority is set to 9, but thread t1 set to priority 9, before setting group1 priority, so it is not affected. But Thread t2 trying to set priority of 9, after setting the group maximum priority of 8, So Thread t2 limited to its priority 8.   



Active Threads of Group                                                 Get Maximum priority                                                 Home

No comments:

Post a Comment