有没有办法知道在给定的时间点有多少可运行对象正在等待 ExecutorService
执行。例如,假设循环调用 execute 方法的速度快于 runnable 可以完成的速度并且累积了盈余,是否有办法获取累积的 runnable 的运行计数?
ExecutorService es = Executors.newFixedThreadPool(50);
while (test) {
es.execute(new MyRunnable());
}
最佳答案
Is there any way to know at a given point in time how many runnables are waiting to be executed by the ExecutorService.
是的。不要使用 Executors...
调用,您应该实例化您自己的 ThreadPoolExecutor
.以下是 Executors.newFixedThreadPool(50)
返回的内容:
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 50,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
一旦你有了ThreadPoolExecutor
,它就有了一个number of getter methods。为您提供池中的数据。未完成工作的数量应该是:
threadPool.getQueue().getSize();
ThreadPoolExecutor
还提供:
getActiveCount()
getCompletedTaskCount()
getCorePoolSize()
getLargestPoolSize()
getMaximumPoolSize()
getPoolSize()
getTaskCount()
如果您想限制队列中的作业数量以免超前太多,您应该使用有界 BlockingQueue
和 RejectedExecutionHandler
。在这里查看我的答案:Process Large File for HTTP Calls in Java
关于java - 如何查找等待执行的可运行对象的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18985691/