Following is the declaration for java.lang.ThreadGroup class:
public class ThreadGroup
extends Object
implements Thread.UncaughtExceptionHandlerThreadGroups form a tree structure. If we create a
ThreadGroup child
for a
ThreadGroup parent
,
parent ThreadGroup
will become
Parent for
child ThreadGroup
. If a parent ThreadGroup is destroyed
all the sub ThreadGroups are destroyed.
Following is the declaration for
java.lang.ThreadGroup
class:
public class ThreadGroup
extends Object
implements Thread.UncaughtExceptionHandler
Constructors :
Following are the ThreadGroup methods :
Methods :
Example Program :
ThreadGroupDemo
class ThreadGroupDemo
{
public static void main(String[] args)
{
ThreadGroup readingThreads = new ThreadGroup("ReadingThreadGroup"); // LINE A
for (int i = 1; i <= 3; i++)
{
A thread = new A(readingThreads, "Thread-" + i); // LINE B
thread.start();
}
ThreadGroup writingThreads = new ThreadGroup("WritingThreadGroup"); // LINE C
for (int i = 4; i <= 6; i++)
{
B thread = new B(writingThreads, "Thread-" + i); // LINE D
thread.start();
}
}
}
class A extends Thread
{
A(ThreadGroup tg, String name)
{
super(tg, name);
}
public void run() // LINE E
{
System.out.println("I am " + Thread.currentThread().getName() + " I belong to " + Thread.currentThread().getThreadGroup().getName());
System.out.println("I am running."); // LINE F
}
}
class B extends Thread
{
B(ThreadGroup tg, String name)
{
super(tg, name);
}
public void run()
{
System.out.println("I am " + Thread.currentThread().getName() + " I belong to " + Thread.currentThread().getThreadGroup().getName());
System.out.println("I am running.");
}
}
OUTPUTI am Thread-2 I belong to ReadingThreadGroup
I am running.
I am Thread-4 I belong to WritingThreadGroup
I am running.
I am Thread-6 I belong to WritingThreadGroup
I am running.
I am Thread-1 I belong to ReadingThreadGroup
I am running.
I am Thread-3 I belong to ReadingThreadGroup
I am running.
I am Thread-5 I belong to WritingThreadGroup
I am running.
DESCRIPTIONIn the above program we have two class A
and B
which extends Thread
. At LINE A
we are created a ThreadGroup ReadingThreadsGroup with reference readingThreads
.
At LINE B
we created three threads for A
and added them to readingThreads
Group by using the Thread class constructor Thread(ThreadGroup reference, String threadName)
. At LINE C
we created a ThreadGroup WritingThreadsGroup with reference writngThreads
. At LINE D
we created three threads for B
and added them to writngThreads
Group. We started all the threads by invoking thread's start
method which in turn invokes thread's run method. At LINE E
inside run
method we are printing the statement the threadname and it's threadgroup. At LINE F we are printing the statement I am running. We implemented the same method in the B class run method as well.
THINGS TO TRY
- 1. Create one more ThreadGroup coordinatingThreads.
2. Create three threads to B
3. Add the created threads to threadgroup and start them.