Wait for all threads in an Executor to finish?

。_饼干妹妹 提交于 2019-12-05 11:29:04
Kevin Day

What type of executor are you using?

ThreadPoolExecutor.awaitTermination() will do what you are asking about (it's effectively a bulk join operation).

As a total aside, ThreadPoolExecutor will allow you to set limits on the # of threads, etc... (might be better than going recursive like what you are doing if the thread count goes high, not sure).

PS - I doubt that executors will make your code run any faster, but they may make your code easier to read and maintain. Using a Thread pool will make things faster for this sort of algorithm, and the Executor makes it easy to work with thread pools.

TofuBeer

Take a look at Executors.newFixedThreadPool which lets you create a pool of at most n threads (gets rid of your "if") and the ExecutorService.shutdown method and the ExecutorsService.awaitTermination method.

You could use a CountDownLatch

PS - I doubt that executors will make your code run any faster, but they may make your code easier to read and maintain. Using a Thread pool will make things faster for this sort of algorithm, and the Executor makes it easy to work with thread pools.

This is not correct.

The executor can be 'backed' by any number of different execution systems including pooled threads.

You need to call the factory class correctly.

Furthermore you also need to decide on a policy for dealing with situations where jobs are submitted to the queue faster than they can be consumed, because you may not initially run out of memory due to limits on the thread execution, but if you queue millions of jobs, then they have to be stored some place whilst they wait for execution.

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