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 t
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;
}
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.
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
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.
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.