我需要获取 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/