最近参加一个面试,被问到一个问题:一个类中可以使用多少个asynctask?通过使用 execute 方法,您将通过调用 asynctask 使用。所以一个类中asynctask的最大限制是抛给我的问题。
这个问题的答案是什么?有人可以解释一下数量和原因吗?
最佳答案
这个问题本身没有任何意义。您可以根据需要在一个类中使用任意多个 AsyncTask
,如果对此有限制,那将是荒谬的。我假设他的意思是可以同时执行多少 AsyncTask
以及它们是如何执行的,对此的答案是:这取决于。
AsyncTasks
可以串行或并行执行。默认行为取决于设备的 API 级别。 documentation AsyncTask
的 execute()
说:
Note: this function schedules the task on a queue for a single background thread or pool of threads depending on the platform version. When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting HONEYCOMB, tasks are back to being executed on a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use.
话虽如此,您可以选择是并行执行还是串行执行,如下所示:
// Executes the task in parallel to other tasks
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Adds the task to a queue and executes one at a time.
asyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
然而,即使您并行运行任务,同时运行的任务数量也是有限的。要找出该限制在哪里,您必须查看 source code of AsyncTask .
直到 Android 4.3 (Jelly Bean),这些限制被硬编码为这些值:
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 1;
但是随着 Android 4.4 的改变,限制是根据设备中使用的处理器计算的:
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
ThreadPoolExecutor
的实现在两种情况下保持不变:
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
所以这应该可以很好地回答您的问题。但是如果你真的想了解 AsyncTask
是如何工作的,那么你应该自己研究源代码! This link leads to the AsyncTask implementation on Android 4.4 .
关于android - android类中可以使用多少个异步任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075422/