从executor服务池(JAVA)中查找等待线程的作业数?

从executor服务池(JAVA)中查找等待线程的作业数?,java,multithreading,Java,Multithreading,我有一个服务器,它有多个使用java executorService实现的工作线程(即线程池) 我的问题是,我不能每秒记录一次,如果线程池中没有空闲线程可用,那么等待处理的作业的长度 注意:日志记录不是我的问题,但我希望能够看到有多少任务/作业等待工作线程处理,是否仍然可以看到executor服务中等待队列(而不是线程池)的长度 我不知道如何实现这一点。ThreadPoolExecutor构造函数接受一个BlockingQueue参数,该参数是用于存储等待的作业的队列实现。您可以使用getQue

我有一个服务器,它有多个使用java executorService实现的工作线程(即线程池)

我的问题是,我不能每秒记录一次,如果线程池中没有空闲线程可用,那么等待处理的作业的长度

注意:日志记录不是我的问题,但我希望能够看到有多少任务/作业等待工作线程处理,是否仍然可以看到executor服务中等待队列(而不是线程池)的长度


我不知道如何实现这一点。

ThreadPoolExecutor构造函数接受一个
BlockingQueue
参数,该参数是用于存储等待的作业的
队列
实现。您可以使用
getQueue()
方法请求此队列,然后检查队列的大小:

System.out.println("Number of waiting jobs: "+executor.getQueue().size());
请注意,此方法在
ExecutorService
接口中不可用,因此最好显式构造
ThreadPoolExecutor
,而不是使用
Executors。newFixedThreadPool
和朋友:

ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
ThreadPoolExecutor executor=新的ThreadPoolExecutor(nThreads,nThreads,
0L,时间单位为毫秒,
新建LinkedBlockingQueue());

虽然OpenJDK/OracleJDK中的
Executors.newFixedThreadPool
也执行相同的操作,但没有指定它,因此使用
(ThreadPoolExecutor)Executors.newFixedThreadPool(nThreads)
可能会在未来的Java版本或替代JDK实现中导致
ClassCastException

如果可以假设服务器使用的
ExecutorService
实现是
ThreadPoolExecutor
,则可以使用
getQueue()方法
返回尚未分配给
工作人员的任务数

/**
 * Returns the task queue used by this executor. Access to the
 * task queue is intended primarily for debugging and monitoring.
 * This queue may be in active use.  Retrieving the task queue
 * does not prevent queued tasks from executing.
 *
 * @return the task queue
 */
public BlockingQueue<Runnable> getQueue() {
    return workQueue;
}

正如建议的那样,使用ThreadPoolExecutor而不是ExecutorService。 您可以利用ThreadPoolExecutor类中存在的阻塞队列。这将提供等待的线程数

ThreadPoolExecutor类还有一些方法可以获取提交任务和已执行任务的计数

参考


希望这能有所帮助

是否有办法获取等待轮询arrayblockingqueue中某些资源的线程数?@LoveMeow,我怀疑。但是您可以检查
ThreadPoolExecutor
的其他方法,如
getTaskCount()
getActiveCount()
,等等。它们可能会回答您的问题。
 if(LOGGER.isDebugEnabled()) {
    LOGGER.debug(String.format("Pending tasks: %d", executor.getQueue().size()));
 }