Default thread group

Every thread in Java has a thread group. The default thread group is ‘main’.

public static void main(String[] args) {
  System.out.printf("ThreadGroup of main thread is: %s\n", Thread
.currentThread().getThreadGroup().getName());
}

Output of above code:
ThreadGroup of main thread is: main

If a thread ‘t’ is spawned from a main thread then the thread group of ‘t’ is ‘main’ as long as ‘t’ doesn’t belongs to another thread group.

public static void main(String[] args) {
  System.out.printf("ThreadGroup of main thread is: %s\n", Thread
.currentThread().getThreadGroup().getName());
  Thread t = new Thread(new WorkerTask());
  t.start();
}

Output of above code:
ThreadGroup of main thread is: main
ThreaGroup of spawned thread is: main

The following snippet showing a spawned thread can be part of a different thread group.

public static void main(String[] args) {
  System.out.printf("ThreadGroup of main thread is: %s\n", Thread
.currentThread().getThreadGroup().getName());
  ThreadGroup tg = new ThreadGroup("OtherThreadGroup");
  Thread t = new Thread(tg, new WorkerTask());
  t.start();
}

Output of above code:
ThreadGroup of main thread is: main
ThreaGroup of spawned thread is: OtherThreadGroup

Advertisements
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s