Executors.newSingleThreadExecutor() - 如何查看队列中有多少任务

发布于 2024-11-05 04:37:39 字数 413 浏览 3 评论 0原文

我在代码中使用 Executors.newSingleThreadExecutor() 。 我想监视队列中的任务数量,以检查处理器是否因消息而过载。如何获取当前未完成提交任务的数量? 我期待这样的事情:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Runnable() {...});
executor.submit(new Runnable() {...});
executor.submit(new Runnable() {...});
// do something and get 3
...
// do something and get 2
...
// do something and get 1

谢谢

I am using Executors.newSingleThreadExecutor() in my code.
I want to monitor number of tasks in queue to check that procesor is not overloaded with messages. How can I get a number of not completed submited tasks for curent moment?
I expect something like this:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Runnable() {...});
executor.submit(new Runnable() {...});
executor.submit(new Runnable() {...});
// do something and get 3
...
// do something and get 2
...
// do something and get 1

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

锦爱 2024-11-12 04:37:39

万一您想保证即使使用新版本的 JVM,FlorianOver 建议的代码也能工作,您可以这样做:(对于方法 Executors.newSingleThreadExecutor() 将不再返回类型的实例线程池执行器)

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

// ...

int queueSize = executor.getQueue().size();

Just in case you want to guarantee that even with new versions of the JVM the code suggested by FlorianOver will work, you could do it this way: (For the case that the method Executors.newSingleThreadExecutor() will no longer return an instance of type ThreadPoolExecutor)

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

// ...

int queueSize = executor.getQueue().size();
許願樹丅啲祈禱 2024-11-12 04:37:39

不是这样的吗?

((ThreadPoolExecutor) executor).getQueue().size();

Isn't it like this?

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