I want to start a ThreadGroup
which contains many threads, but the start()
method is not present in the ThreadGroup
class. It has a stop()
method to stop the thread group though.
How can I start the thread group if the start()
method is not available?
Please see the below code, I can start thread one by one but cannot start the thread group, because start()
method is not present in ThreadGroup
class. The requirement is we need to start thread group at the same time, how can this be done?
public class ThreadGroupExample
{
public static void main(String[] args)
{
ThreadGroup thGroup1 = new ThreadGroup("ThreadGroup1");
/* createting threads and adding into thread grout "thGroup1" */
Thread1 th1 = new Thread1(thGroup1, "JAVA");
Thread1 th2 = new Thread1(thGroup1, "JDBC");
Thread2 th3 = new Thread2(thGroup1, "EJB");
Thread2 th4 = new Thread2(thGroup1, "XML");
/* starting all thread one by one */
th1.start();
th2.start();
th3.start();
th4.start();
// thGroup1.start();
thGroup1.stop();
}
}
class Thread1 extends Thread
{
Thread1(ThreadGroup tg, String name)
{
super(tg, name);
}
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
ThreadGroup tg = getThreadGroup();
System.out.println(getName() + "\t" + i + "\t" + getPriority()
+ "\t" + tg.getName());
}
}
}
class Thread2 extends Thread
{
Thread2(String name)
{
super(name);
}
Thread2(ThreadGroup tg, String name)
{
super(tg, name);
}
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
ThreadGroup tg = getThreadGroup();
System.out.println(getName() + "\t" + i + "\t" + getPriority()
+ "\t" + tg.getName());
}
}
}
From the docs:
A thread group represents a set of threads.
It is not designed to .start()
multiple threads at the same time.
You can add Threads
to the group, or other ThreadGroups
, which can access other Thread
s' state, but not start a ThreadGroup
together. A Thread
is allowed to access information about its own ThreadGroup
, but not to access information about its ThreadGroup
's parent ThreadGroup
or any other ThreadGroups
.
For some more info about the available functions with example of usage read here.