ThreadPoolExecutor's getActiveCount()

南笙酒味 提交于 2019-12-04 09:19:46

As the JavaDoc of getActiveCount states, it's an approximate value: you should not base any major business logic decisions on this.

If you want to wait for all scheduled tasks to complete, then you should simply use

pool.shutdown();
pool.awaitTermination(terminationTimeout, terminationTimeoutUnit);

If you need to wait for a specific task to finish, you should use submit() instead of execute() and then check the Future object for completion (either using isDone() if you want to do it non-blocking or by simply calling get() which blocks until the task is done).

The documentation suggests that the method getActiveCount() on ThreadPoolExecutor is not an exact number:

getActiveCount

public int getActiveCount()

Returns the approximate number of threads that are actively executing tasks.

Returns: the number of threads

Personally, when I am doing multithreaded work such as this, I use a variable that I increment as I add tasks, and decrement as I grab their output.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!