AsyncTask keeps waiting?

后端 未结 2 1571
被撕碎了的回忆
被撕碎了的回忆 2020-12-18 08:53

A button in one of my activities calls an AsyncTask that updates the underlying Cursor for a ListView\'s SimpleCursorAdapter. Everytime I click the button, a new thread for

2条回答
  •  渐次进展
    2020-12-18 09:30

    AsyncTask under the hood uses a ThreadPoolExecutor. Those threads might not go away for a bit because it'd be a waste to keep creating and tearing down those threads too often. After a while if you create more AsyncTasks you'll find that it'll stop creating new threads and it'll re-use the old ones.

    Update to address some details:

    You would think that if there are free threads in the pool, it wouldn't create new ones, but this isn't exactly true. The idea is that there's a certain number of threads that are useful to have around to keep processing asynchronous tasks. This is called the core pool size. In Android's AsyncTask case, they seem to have set it to 5. If you look at the documentation for ThreadPoolExecutor it says:

    When a new task is submitted in method execute(Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle.

    There's also a maximum fittingly called the maximum pool size.

提交回复
热议问题