java - 如何查找等待执行的可运行对象的数量

标签 java concurrency threadpool

有没有办法知道在给定的时间点有多少可运行对象正在等待 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()

如果您想限制队列中的作业数量以免超前太多,您应该使用有界 BlockingQueueRejectedExecutionHandler。在这里查看我的答案:Process Large File for HTTP Calls in Java

关于java - 如何查找等待执行的可运行对象的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18985691/

相关文章:

java - 当 Spring SecurityContextHolder 在 getPrincipal 上返回 null 时,应该抛出哪个异常?

java - 如何以编程方式检查 AppEngine 应用程序版本是否已存在

java - 收到 ConcurrentModificationException 但我没有删除

c# - 从 HttpClient SendAsync 请求获取响应时出现无法解释的超时和延迟

java - 如果我们更改字符串值,字符串池如何管理引用?

java - Spring Boot 指定 Hibernate 类而不是指定包

node.js - Node.js 是否支持并行性?

java - 生产消费者

scala - 光滑的 AsyncExecutor 异常

C++ 线程池