ExecutorService中的活动线程

时间:2020-03-05 18:58:10  来源:igfitidea点击:

有什么想法如何确定当前在ExecutorService中运行的活动线程的数量?

解决方案

回答

使用ThreadPoolExecutor实现并对其调用getActiveCount():

int getActiveCount() 
// Returns the approximate number of threads that are actively executing tasks.

ExecutorService接口没有为此提供方法,它取决于实现。

回答

在线程上放置一个静态易失性计数器,该线程在激活和停用时都会更新。
另外,请参阅API。

回答

检查Executors.newFixedThreadPool()的源代码:

return new ThreadPoolExecutor(nThreads, nThreads,
                              0L, TimeUnit.MILLISECONDS,
                              new LinkedBlockingQueue<Runnable>());

ThreadPoolExecutor具有getActiveCount()方法。因此,我们可以将ExecutorService强制转换为ThreadPoolExecutor,或者直接使用上述代码来获取一个代码。然后,我们可以调用getActiveCount()。

回答

ExecutorService接口未定义检查池中辅助线程数的方法,因为这是实现细节

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

在ThreadPoolExecutor类上可用

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

但这需要我们显式创建ThreadPoolExecutor,而不是使用返回ExecutorService对象的Executors工厂。我们总是可以创建自己的工厂,该工厂返回ThreadPoolExecutors,但是仍然会留下使用具体类型而不是其接口的糟糕形式。

一种可能性是提供我们自己的ThreadFactory,它可以在已知线程组中创建线程,然后我们就可以计数

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