如何从ThreadPoolExecutor获取当前运行和排队的线程数?

时间:2015-10-01 21:12:01

标签: java multithreading concurrency executorservice threadpoolexecutor

我需要在ThreadPoolExecutor中获取正在运行的线程数,以及队列大小。

我有一个工作实现(跟踪arraylist中的每个期货和未完成的计数):

java.util.concurrent.ArrayBlockingQueue<Runnable> threadpoolQueue = 
    new java.util.concurrent.ArrayBlockingQueue<Runnable>(10);

ThreadPoolExecutor threadpool = new java.util.concurrent.ThreadPoolExecutor(0, 
    executingThreads, retryInterval, java.util.concurrent.TimeUnit.MILLISECONDS, threadpoolQueue);

ArrayList<Future> threads = new ArrayList<Future>();

threads.add(threadpool.submit(/*Runnable*/));

//Get Sizes
int threadpoolRunningThreads = 0;
for (Future obj : threads) {
    if (!obj.isDone()) {
         threadpoolRunningThreads++;
    }
}
logger.debug("Merging all threads threadpool.size=" + threadpoolRunningThreads 
    + ",threadpool.queue.size="+ threadpoolQueue.size());

这是跟踪线程池的一种非常尴尬的方式,我没有看到线程池中提供的任何方法允许获取运行和排队线程的数量。我想做类似的事情:

threadpool.getIncompletedTaskSize();
threadpool.getQueuedTaskSize();

我能实现吗?或者至少比我的实施更容易?我使用 Java 1.6

1 个答案:

答案 0 :(得分:1)

可能是ThreadPoolExecutor#getActiveCount()ThreadPoolExecutor#getQueue()#size()