如何查找等待执行的运行的数量 [英] How to find the number of runnables waiting to be executed

查看:262
本文介绍了如何查找等待执行的运行的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法知道在给定的时间点有多少个可执行文件正在等待由 ExecutorService 执行。例如,假设循环调用execute方法的速度比runnable可以完成的速度快,并且剩余累加,那么是否仍然有累积运行的运行计数?

  ExecutorService es = Executors.newFixedThreadPool(50); 

while(test){
es.execute(new MyRunnable());
}


解决方案


有什么方法可以知道在给定的时间点有多少个可执行文件正在等待由ExecutorService执行。


是的。而不是使用 Executors ... 调用,您应该实例化您自己的 ThreadPoolExecutor 。下面是 Executors.newFixedThreadPool(50)正在返回:

  ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50,50,
0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue< Runnable>());

一旦你拥有 ThreadPoolExecutor getter方法数量,为您提供池上的数据。未完成工作的数量应为:

  threadPool.getQueue()。getSize 

也可从 ThreadPoolExecutor p>


  • getActiveCount()

  • getCompletedTaskCount()

  • getCorePoolSize()

  • getLargestPoolSize()

  • getMaximumPoolSize()

  • getPaskSize()

  • getTaskCount li>


如果您想限制队列中的作业数量,以免过于遥远,您应该使用有界的 BlockingQueue RejectedExecutionHandler 。请参阅我的答案:处理HTTP呼叫的大文件Java


Is there any way to know at a given point in time how many runnables are waiting to be executed by the ExecutorService. For example, assuming that the loop is invoking the execute method faster than the runnable can complete and a surplus accumulates, is there anyway to get a running count of the accumulated runnables?

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.

Yes. Instead of using the Executors... calls, you should instantiate your own ThreadPoolExecutor. Below is what the Executors.newFixedThreadPool(50) is returning:

ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 50,
           0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

Once you have the ThreadPoolExecutor, it has a number of getter methods that give you data on the pool. The number of outstanding jobs should be:

threadPool.getQueue().getSize();

Also available from ThreadPoolExecutor are:

  • getActiveCount()
  • getCompletedTaskCount()
  • getCorePoolSize()
  • getLargestPoolSize()
  • getMaximumPoolSize()
  • getPoolSize()
  • getTaskCount()

If you want to throttle the number of jobs in the queue so you don't get too far ahead, you should use a bounded BlockingQueue and the RejectedExecutionHandler. See my answer here: Process Large File for HTTP Calls in Java

这篇关于如何查找等待执行的运行的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆