Particular Thread Count

后端 未结 5 762
花落未央
花落未央 2021-01-24 01:11

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

相关标签:
5条回答
  • 2021-01-24 01:47

    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;
    }
    
    0 讨论(0)
  • 2021-01-24 01:48

    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.

    0 讨论(0)
  • 2021-01-24 01:50

    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

    0 讨论(0)
  • 2021-01-24 02:07

    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.

    0 讨论(0)
  • 2021-01-24 02:08
       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.

    0 讨论(0)
提交回复
热议问题