/**
* 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;
}
3 回答
ThreadPoolExecutor
构造函数接受BlockingQueue
参数,该参数是用于存储等待作业的Queue
实现 . 您可以使用getQueue()
方法请求此队列,然后检查队列的大小:请注意,此方法在
ExecutorService
界面中不可用,因此最好显式构造ThreadPoolExecutor
而不是使用Executors.newFixedThreadPool
和朋友:虽然OpenJDK / OracleJDK中的
Executors.newFixedThreadPool
执行相同操作,但未指定,因此在将来的Java版本或替代JDK实现中使用(ThreadPoolExecutor)Executors.newFixedThreadPool(nThreads)
可能会导致ClassCastException
.如果您可以假设服务器使用的
ExecutorService
实现是ThreadPoolExecutor
,那么您可以使用方法getQueue()
返回尚未分配给Worker
的任务数 .所以你可以运行这样的东西:
正如建议使用ThreadPoolExecutor而不是ExecutorService . 您可以利用ThreadPoolExecutor类中的阻塞队列 . 这将为您提供等待的线程数 .
ThreadPoolExecutor类也有方法来获取提交的任务和执行任务的计数 .
参考
ThreadPoolExecutor
BlockingQueue
希望这可以帮助