如何查找ScheduledExecutorService线程池中的活动线程和空闲线程的数量?
我们正在为我们的项目使用 ScheduledExecutorService,我想知道如何在执行某些函数之前查找线程池中可用的空闲线程数。
private static final ScheduledExecutorService executor;
executor = Executors.newScheduledThreadPool(16);
public void scheduleTask(){
//I want to check the number of free threads or number of active threads in thread pool so that I can schedule jobs accordingly
executor.scheduleAtFixedRate(this, 0, 2, TimeUnit.HOURS);
我尝试发现有一些方法可以查找 ThreadPoolExecutor 的活动线程数,但找不到 ScheduledExecutorService 的任何方法
We are using ScheduledExecutorService for our project and I would like to know how to find the number of free threads available in the thread pool before executing some functions.
private static final ScheduledExecutorService executor;
executor = Executors.newScheduledThreadPool(16);
public void scheduleTask(){
//I want to check the number of free threads or number of active threads in thread pool so that I can schedule jobs accordingly
executor.scheduleAtFixedRate(this, 0, 2, TimeUnit.HOURS);
I tried and found that there are some methods to find the number of active threads for ThreadPoolExecutor but couldn't find any for ScheduledExecutorService
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
thread.activecount()
方法,以获取活动线程的总量。You can use the
Thread.activeCount()
method, to get the total amount of active Threads.ScheduledExecutorService
是一个抽象接口,它与线程没有真正的关系。它可以由线程以外的其他一些机制支持。需要使用它基于线程的具体实现,即
ScheduledThreadPoolExecutor
。我认为在您的情况下,可以安全地假设Executors.newScheduledThreadPool()
返回以下类型:ScheduledExecutorService
is an abstract interface, it is not really related to threads. It can be backed by some other mechanism than threads.You need to use its specific implementation based on threads, which is
ScheduledThreadPoolExecutor
. I think in your case it is safe to assume thatExecutors.newScheduledThreadPool()
returns exactly this type: