Java 中如何判断线程池是否空闲

发布于 2024-08-05 20:03:25 字数 332 浏览 6 评论 0原文

我有一个使用创建的线程池,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

临风闻羌笛 2024-08-12 20:03:25

您可以子类化 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?

漫漫岁月 2024-08-12 20:03:25

我想知道这是否适用于现实世界的环境。它涉及对 ThreadPoolExecutor 进行子类化并向其传递一个 IdleListener:

  @Override
  protected void beforeExecute(Thread t, Runnable r)
  {
    super.beforeExecute(t, r);
    listener.working();
  }

  @Override
  protected void afterExecute(Runnable r, Throwable t)
  {
    super.afterExecute(r, t);
    long activeCount = getTaskCount() - getCompletedTaskCount();
    if (activeCount == 1) // yes, one
    {
      listener.idle();
    }
  }

接口:

  interface IdleListener
  {
    void working();
    void idle();
  }

I am wondering if this would work in a real world environment. It involves subclassing ThreadPoolExecutor and passing it an IdleListener:

  @Override
  protected void beforeExecute(Thread t, Runnable r)
  {
    super.beforeExecute(t, r);
    listener.working();
  }

  @Override
  protected void afterExecute(Runnable r, Throwable t)
  {
    super.afterExecute(r, t);
    long activeCount = getTaskCount() - getCompletedTaskCount();
    if (activeCount == 1) // yes, one
    {
      listener.idle();
    }
  }

The interface:

  interface IdleListener
  {
    void working();
    void idle();
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文