查找等待执行程序服务池 (JAVA) 中的线程的作业数?
2022-09-03 13:10:45
我有一个服务器,它使用java执行器服务(即线程池)实现多个工作线程
我的问题是,如果线程池中没有空闲线程可用,我无法每秒记录等待处理的作业的长度。
注意:日志记录不是我的问题,但我希望能够看到有多少任务/作业正在等待由工作线程处理,无论如何都可以看到执行器服务中等待队列(不是线程池)的长度吗?
我不知道如何实现这个东西。
我有一个服务器,它使用java执行器服务(即线程池)实现多个工作线程
我的问题是,如果线程池中没有空闲线程可用,我无法每秒记录等待处理的作业的长度。
注意:日志记录不是我的问题,但我希望能够看到有多少任务/作业正在等待由工作线程处理,无论如何都可以看到执行器服务中等待队列(不是线程池)的长度吗?
我不知道如何实现这个东西。
构造函数接受一个参数,该参数是用于存储等待作业的实现。您可以使用方法请求此队列,然后检查队列的大小:ThreadPoolExecutor
BlockingQueue
Queue
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>());
虽然在OpenJDK/OracleJDK中做同样的事情,但没有指定它,因此使用可能会导致在未来的Java版本或替代JDK实现中。Executors.newFixedThreadPool
(ThreadPoolExecutor)Executors.newFixedThreadPool(nThreads)
ClassCastException
如果可以假定服务器使用的实现是 ,则可以使用返回尚未分配给 的任务数的方法。ExecutorService
ThreadPoolExecutor
getQueue()
Worker
/**
* 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;
}
所以你可以运行这样的东西:
if(LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Pending tasks: %d", executor.getQueue().size()));
}