Reputation: 1131
I want to know how many active threads are there for a particular Thread class.
Lets say I have a class T which extends thread. In some other class (Ex: Demo) , I want to get the thread count for the T class Thread. I do know Thread.activeCount()
method but it will get the count for a thread group. It does not server my need here. Lets say I have T1 and T2 classes which extends thread and In the Demo class I want to get How many T2 active threads are there.
How should I achieve this? Any Ideas??
PS: I don't have source code for the Class T1 and T2.
Thanks for the help.
Upvotes: 1
Views: 770
Reputation: 1107
private static int getThreadCount(){
int runningThread = 0;
for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getState()==Thread.State.RUNNABLE && t instanceof YourThreadClassName ) runningThread++;
System.out.println("Active threads : "+runningThread);
return runningThread;
}
Justreplace YourThreadClassName with your class that is extended by Thread.
Upvotes: 0
Reputation: 100259
You can use Thread.enumerate()
:
public int countThreadsOfClass(Class<? extends Thread> clazz) {
Thread[] tarray = new Thread[Thread.activeCount()];
Thread.enumerate(tarray);
int count = 0;
for(Thread t : tarray) {
if(clazz.isInstance(t))
count++;
}
return count;
}
Upvotes: 1
Reputation: 81
Try to use ThreadPoolExecutor
.
You can extend the ThreadPoolExecutor
and counts the number of threads by calling getActiveCount()
.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html
Upvotes: 0
Reputation: 20442
You could implement ThreadFactory to construct the custom Thread classes and supply a ThreadGroup instance to get the counts from. By using ThreadFactory, each instance could contain its own ThreadGroup, making counts accessible based on the factory used.
Upvotes: 0
Reputation: 159135
Your Thread
(or Runnable
) subclass can maintain a static
active count. Increment when run()
starts, decrement when run()
ends (in a finally
block).
Make sure the increment/decrement is done in a multithread secure way.
Upvotes: 0