Tuesday 4 March 2014

Thread Groups

Java provides a facility that user can group threads, and provide securities, priorities based on the group. There is only one root thread group, and a root thread group contains threads and other thread groups. Same applicable to other thread groups also, a thread group can contain other threads or other thread groups.


A Thread belongs to exactly one group. Thread Groups are similar to directories in System. Threads in the Thread group are similar to files in a directory. A directory can contain other directories and files, like that a Thread group can contain other thread groups and threads.

As we know, there is always a thread called main thread runs, whenever the main method called. The main thread by default in the thread group “main”.

Below is the toString() implementation for the Thread class. When a thread object is called in the print method, toString() is invoked by default.

public String toString() {
 ThreadGroup group = getThreadGroup();
 if (group != null) {
  return "Thread[" + getName() + "," + getPriority() + "," + group.getName() + "]";
 } 
 else {
  return "Thread[" + getName() + "," + getPriority() + "," + "" + "]";
 }
}

As you observe, it prints thread name followed by priority of the thread followed by Thread group name, if it exists.

class ThreadEx{
 public static void main(String args[]){
  System.out.println(Thread.currentThread());
 }
}
   
Output
Thread[main,5,main]

Thread[main,5,main] : "main" is the thread name
Thread[main,5,main] :5 is the priority of the thread
Thread[main,5,main] :"main" is the group name of the current thread.

Display active threads                                                 Create Thread Group                                                 Home

No comments:

Post a Comment