Thursday, June 16, 2016

Thread Priorities and Thread Group example java

Thread Priorities 

When the threads are created and started, a thread scheduler program in JVM will load them into memory and execute them.This scheduler will allot more JVM time to those threads which are having higher priorities. Thread priorities vary from 1 to 10 .

What is default priority of a thread?
Ans: Default Priority=5

Program:

/**
 * @author Abhinaw.Tripathi
 *
 */

class ThreadPriorityClss extends Thread
{
int count=0;
public void run()
{
for(int i=1;i<=10000;i++)
count ++;
System.out.println("Completed Thread:" + Thread.currentThread().getName());
System.out.println("Its priority:"+Thread.currentThread().getPriority());
}
}
public class ThreadPriorityApp
{
public static void main(String[] args)
{
ThreadPriorityClss obj=new ThreadPriorityClss();
Thread t1=new Thread(obj,"One");
Thread t2=new  Thread(obj, "Two");

t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);

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


}

Output:

Completed ThreadTwo
Its priority:5
Completed ThreadOne
Its priority:2

Thread Group

A thread group represents several thread as a single group.The main advantage of taking several threads as a group is that by using a single  method,we will be able to control all the threads in the group.

To create a thread group,we should simply create an object to ThreadGroup class as:

ThreadGroup tg=new ThreadGroup("groupName");

Normally,the maximum priority of a thread group will be 10 .

Program:

/**
 * @author Abhinaw.Tripathi
 *
 */
class Reservation extends Thread
{
public void run()
{
System.out.println("I am reservation thread.");
}
}

class Cancellation extends Thread
{
  public void run()
  {
 System.out.println("I am cancellation thread.");
  }
}

public class ThreadGroupApp
{
public static void main(String[] args)
{
Reservation res=new Reservation();
Cancellation cancel=new Cancellation();
ThreadGroup tg=new ThreadGroup("First Group");
Thread t1=new Thread(tg, res,"First Thread");
Thread t2=new Thread(tg, cancel, "Second Thread");
ThreadGroup tg1=new ThreadGroup(tg,"Second Group");
Thread t3=new Thread(tg1, res,"Third Thread");
Thread t4=new Thread(tg1, cancel, "Four Thread");
System.out.println("parent of tg1:" +tg1.getParent());
tg1.setMaxPriority(7);
System.out.println("Thread Group of t1:" +t1.getThreadGroup() );
System.out.println("Thread Group of t3:" +t3.getThreadGroup() );
t1.start();
t2.start();
t3.start();
t4.start();
System.out.println("No of threads active in tg="+tg.activeCount());
}
}

Output:


parent of tg1:java.lang.ThreadGroup[name=First Group,maxpri=10]

Thread Group of t1:java.lang.ThreadGroup[name=First Group,maxpri=10]
Thread Group of t3:java.lang.ThreadGroup[name=Second Group,maxpri=7]
I am reservation thread.
I am cancellation thread.
No of threads active in tg=2
I am reservation thread.
I am cancellation thread.



No comments: