I am learning the concept of multi-threading, where i was trying to find the number of active threads in an array, but the method of ThreadGroup.activeCount() is only returning zero value for it.
Here is the code:
Thread object class :-
class th1 extends Thread
{
public th1(String threadName, ThreadGroup tg1)
{
super(tg1, threadName);
}
@Override
public void run()
{
try {
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is running");
}
}
main class :-
public class enumerate_demo
{
public static void main(String[] args)
{
ThreadGroup tg1 = new ThreadGroup("group 1");
Thread t1 = new Thread(new th1("t-1", tg1));
t1.start();
Thread t2 = new Thread(new th1("t-2", tg1));
t2.start();
Thread t3 = new Thread(new th1("t-3", tg1));
t3.start();
System.out.println("Number of active count :- " + tg1.activeCount());
Thread[] group = new Thread[tg1.activeCount()];
int count = tg1.enumerate(group);
for (int i = 0; i < count; i++)
{
System.out.println("Thread " + group[i].getName());
}
}
}
The issue is that while creating instances th1
class you are using them as Runnable
as oppose to Thread
. And those wrapper threads aren't associated with any ThreadGroup
. Declare variables as follows.
Thread t1 = new th1("t-1", tg1);
t1.start();