Active threads in ExecutorService

后端 未结 6 1533
盖世英雄少女心
盖世英雄少女心 2020-12-23 19:16

Any ideas how to determine the number of active threads currently running in an ExecutorService?

6条回答
  •  星月不相逢
    2020-12-23 19:19

    The ExecutorService interface does not define a method to examine the number of worker threads in the pool, as this is an implementation detail

    public int getPoolSize()
    Returns the current number of threads in the pool.
    

    Is available on the ThreadPoolExecutor class

    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    
    public class PoolSize {
    
        public static void main(String[] args) {
            ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());
            System.out.println(executor.getPoolSize());
        }
    }
    

    But this requires you to explicitly create the ThreadPoolExecutor, rather than using the Executors factory which returns ExecutorService objects. You could always create your own factory that returned ThreadPoolExecutors, but you would still be left with the bad form of using the concrete type, not its interface.

    One possibility would be to provide your own ThreadFactory which creates threads in a known thread group, which you can then count

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ThreadFactory;
    
    
    public class PoolSize2 {
    
        public static void main(String[] args) {
            final ThreadGroup threadGroup = new ThreadGroup("workers");
    
            ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    return new Thread(threadGroup, r);
                }
            });
    
            System.out.println(threadGroup.activeCount());
        }
    }
    

提交回复
热议问题