-->

Is there a limit of AsyncTasks to be executed at t

2020-02-01 04:35发布

问题:

This should have an easy answer, yet I couldn't find any. And since I'm still an android dummy I came here to ask you people.

I've been making this project that executes 10 AsyncTasks on the startup. Each task contains 3 URLs that collect data there and do nothing important in the app (yet).

I also have 10 textviews which I use to keep track of the progress of the AsyncTasks.

When a task starts the appropriate textview is put on "Start" When a task is progressing it sets its appropriate textview to "Downloading" When a task is finished it sets its appropriate textview to "Finished"

This is what I observed and came to question about the AsyncTask. When I start the app I notice 5 of the textviews being switched to the "Downloading" marker, so I see 5 AsyncTasks doing their job as they should. When done it starts up a new AsyncTask. Yet they never reach over that limit of 5.

What causes this limit of 5 AsynchTasks running at the same time? Did I cause this in some file which I cannot find? Is this a limit of android 2.3.3? Maybe a limit of the device I'm using to sim the app?

Can anyone elaborate for me?

回答1:

Yes, there's a limit. AsyncTask is backed by a ThreadPoolExecutor with a core pool size of 5, but a maximum pool size of 128 (from 1.6 - 4.0.3), so really I would think you should see all 10 of yours run at once. You can't change it though. If you really want to do something different (and I wouldn't recommend it unless you have a very specific reason), you'll have to do something custom with a larger pool size or just spin up a bunch of threads manually.

Update:

Here's what the docs say:

If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full.

So that's why. Your queue isn't full, so it just keeps it at the core pool size.



回答2:

The ThreadPoolExecutor has a corePoolSize, a maxPoolSize and a QueueCapacity. If all of your threads from the corePoolSize are used, any other task are put in the queue of each of the threads from the core pool. After these queues are full, a new thread is being initialized, as long as it is within the limits of the maxPoolSize.

The catch here is that the queues of each thread ( unless changed programatically ) are UNBOUNDED. That means that all of your threads from the core pool size are used, and any other tasks are queued and wait for their turn with one of the core threads. They never get a chance to reach the max pool size.

You have to configure your own Executor and change the queue capacity. Good luck!