Android 并行执行多个 AsyncTask

Android Execute Multiple AsyncTask Parallely

你好我对在 Android

中并行执行多个异步任务有点困惑

在 Donut 之前它只是单一处理意味着我们一次只能执行一个任务,但后来它发生了变化,我们可以并行执行多个异步任务,在那种情况下也有执行多个异步任务的限制,我们可以一次只执行 138 个 Async Task 线程,否则它会通过异常,但后来 honeycomb 它发生了变化,我们可以一次执行 5 个异步任务,10 个可以在等待队列中,但是如果我们一次执行超过 15 个异步任务意味着如果我一次执行 16 个任务那么它将并行执行 6 个任务并且 10 个将在队列中,这意味着等待队列中至少有 10 个任务等待工作线程完成,稍后在 Kitkat 中它已经更改,它首先获取当前在 Vm 中的处理器数量 运行,并根据它执行多个异步任务。

现在我的问题是:

  1. 并行执行多个异步任务有什么问题。

  2. 为什么限制一次只能执行138个asynctask

  3. 为什么它与 android 版本不同。

  4. 在 kitkat 中获取 VM 中当前 运行 的处理器数量并据此执行异步任务的确切含义是什么。

  5. asynctask 在后台使用什么来跟踪等待的 asynctask 和 运行 任务。

请回答我的问题。

引用 AsyncTask class 来自 Android 开发者

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

在内部,AsyncTask 是通过 Executor 实现的,默认的是 SerialExecutor

限制 == CPU 核心数量的要点是,如果限制更大,则启动的线程之间将不断竞争。你知道一天结束的时候你可以让线程同时工作。在许多情况下,线程之间的这种竞争不是问题,但在某些情况下却是问题。我想 Google 只是认为利大于弊,这就是他们再次返回 SerialExecutor 的原因。再次引用 AsyncTask class 描述:

Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

这些问题主要是InterruptedExceptionIllegalStateException

最后,如果您真的知道自己在做什么,并且有充分的理由覆盖 Google 的默认行为,您可以使用 AsyncTask.executeOnExecutor(Executor, Object[]),传入 [=18] =].