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

标签 java multithreading concurrency executorservice threadpoolexecutor

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

我有一个有效的实现(跟踪数组列表中的每个 future 并计算未完成的数量):

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

最佳答案

也许ThreadPoolExecutor#getActiveCount()ThreadPoolExecutor#getQueue()#size()

关于java - 如何从 ThreadPoolExecutor 获取当前正在运行和排队的线程数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32896946/

相关文章:

java - 多个错误通知

java - 为什么在实现 Runnable 时使用 Thread.currentThread().isInterrupted() 而不是 Thread.interrupted()?

c++ - 在单独的线程 Qt 中渲染屏幕外小部件

java - 有没有办法对 AtomicReference 设置锁定

java - 在 Java 中阻塞并同时释放可变数量的线程

python - Gunicorn 一次响应的请求不超过 6 个

java - 为每个类对象共享通用处理代码的最简洁、最有效的方法是什么?

java - 可以阻止 JIT 优化方法吗?

java - JSP:在mysql查询中执行非英文字符

java - 多线程应用程序中编译时和运行时类路径不匹配的原因是什么?