Java 中如何判断线程池是否空闲
我有一个使用创建的线程池,
java.util.concurrent.ThreadPoolExecutor
我可以等到池空闲吗?我的意思是所有线程都没有运行,队列中没有任何东西在等待。
我搜索了网络,所有解决方案都不适合我。例如,我不想关闭池,因此 awaitTermination()
不起作用。我也知道如何 getTaskCount()
但我不想继续轮询池,这会浪费 CPU。
这是一个大型项目,我不想更改池中运行的所有任务,因此我正在寻找一些不依赖于任务协作的解决方案。所以闩锁或障碍物对我不起作用。
I have a thread pool created using
java.util.concurrent.ThreadPoolExecutor
Is there anyway I can wait till the pool is idle? By which I mean all the threads are not running and nothing is waiting in the queue.
I searched the web and all the solutions don't work for me. For example, I don't want shutdown the pool so awaitTermination()
wouldn't work. I also know how to getTaskCount()
but I don't want keep polling the pool, which wastes CPU.
This is a large project and I don't want change all the tasks running in the pool so I am looking for some solution that don't rely on task cooperation. So latches or barriers don't work for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以子类化 ThreadPoolExecutor 并使用 beforeExecute 和 afterExecute 添加挂钩来跟踪任务执行情况,包括计算当前正在执行的任务的基本数学。还可以使用 getQueue() 直接访问队列。
在这些之间,您可以轻松实现您要求的跟踪。
我很好奇你的用例是什么......当池空时你会怎么处理它?
You could subclass ThreadPoolExecutor and add hooks with beforeExecute and afterExecute to track task execution however you like, including basic math to count the currently executing tasks. There is also direct access to the Queue with getQueue().
Between these you can easily implement the tracking you ask for.
I'm curious what your use case is... what will you do with the pool when it is empty?
我想知道这是否适用于现实世界的环境。它涉及对 ThreadPoolExecutor 进行子类化并向其传递一个 IdleListener:
接口:
I am wondering if this would work in a real world environment. It involves subclassing
ThreadPoolExecutor
and passing it anIdleListener
:The interface: