使用ThreadPoolExecutor的活动任务数 [英] Number of active tasks using ThreadPoolExecutor
问题描述
我正在使用ThreadPoolExecutor在Java应用程序中执行任务.我有一个要求,我想在任何时间获取执行者队列中队列中活动任务的数量.我查看了 javadoc ThreadPoolExecutor,发现了两个相关方法:getTaskCount()
和getCompletedTaskCount()
.
I am using a ThreadPoolExecutor to execute tasks in my Java application. I have a requirement where I want to get the number of active tasks in the queue at any point in time in the executor queue . I looked up at the javadoc for ThreadPoolExecutor and found two relevant methods: getTaskCount()
and getCompletedTaskCount()
.
根据文档,我可以分别通过上述两种方法获得计划任务和完成任务的数量.但是我找不到能够在任何时间获取队列中活动任务数量的解决方案.我可以做类似的事情:
Per the documentation, I could get the number of scheduled tasks and completed tasks from the above two methods respectively. But I am not able to find a solution for getting the number of active tasks in the queue at any point in time. I can do something like:
getTaskCount() = getCompletedTaskCount() + failed tasks + active tasks
但是失败的任务数量不能直接用于进行预期的计算.
But the number of failed tasks is not directly available to arrive at the intended calculation.
我在这里想念东西吗?
推荐答案
我认为您不需要通过尝试使用的计算来了解失败的计数.
I don't think you need to know the failed count with the calculation you're trying to use.
long submitted = executor.getTaskCount();
long completed = executor.getCompletedTaskCount();
long notCompleted = submitted - completed; // approximate
(大约)足够.
或者,您可以使用 size()
:
Alternatively, you can use getQueue()
with size()
:
int queued = executor.getQueue().size();
int active = executor.getActiveCount();
int notCompleted = queued + active; // approximate
此答案假定您正在寻找尚未完成"的数字.您的问题本身矛盾,因此我不确定您要问什么.如果这是不正确的,请回复我对您问题的评论,我将相应地更新此答案.
这篇关于使用ThreadPoolExecutor的活动任务数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!