Tuesday, 4 March 2014

Create a Thread Group

ThreadGroup class provides two constructors to create a thread group.

1. public ThreadGroup(String name)
Constructs a new thread group. The parent of this new group is the thread group of the currently running thread.

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

  System.out.println("Thread Group Name is " + group1.getName());
  System.out.println("Parent group of the new Thread group is " + group1.getParent().getName());
 }
}

Output
Thread Group Name is Group1
Parent group of the new Thread group is main

As you observe, the new thread group created in the main method, Which runs in main thread and main thread is part of main thread group. So the parent for the new thread group is “main”. GetParent() returns the parent group of the current thread group. GetName() returns the thread group name.

2. public ThreadGroup(ThreadGroup parent, String name)
Creates a new thread group. The parent of this new group is the specified thread group.   

class ThreadEx{
 public static void main(String args[]){
  ThreadGroup group1 = new ThreadGroup("Group1");
  ThreadGroup group2 = new ThreadGroup(group1, "Group2");

  System.out.println("Thread Group group2 parent is " + group2.getParent().getName());
  System.out.println("Thread Group group1 parent is " + group1.getParent().getName());
 }
}

Output
Thread Group group2 parent is Group1
Thread Group group1 parent is main
   


Thread Groups                                                 Add thread to thread group                                                 Home

No comments:

Post a Comment