Particular Thread Count

时光怂恿深爱的人放手 提交于 2019-12-20 05:35:17

问题


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.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/32326388/particular-thread-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!