我想在android中使用AsyncTask并行发送多个请求到服务器
那我该怎么做呢?
我见过像这样的代码
myAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,参数)
但它不是并行运行,而是串行运行。
请帮帮我。
我想在android中使用AsyncTask并行发送多个请求到服务器
那我该怎么做呢?
我见过像这样的代码
myAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,参数)
但它不是并行运行,而是串行运行。
请帮帮我。
嘿,executeonExecutor 应该可以完美运行。
您将需要使用线程池 Executor 来执行 Asynctask 。默认实现使用在单个线程上运行的串行执行器
所以创建一个 ThreadPoolExeecutor 然后使用
Asynctask 的 executeonExecutor 而不是仅仅执行方法
Honeycomb 版本中的 AsyncTask 发生了变化。旧版本有一个 10 个线程的线程池,因此您可以并行运行 10 个任务。但是对于 Honeycomb 及更高版本,默认是串行执行器,它会一个接一个地执行任务。但是你可以传递一个 ThreadPoolExecutor 来执行:
if (Build.VERSION.SDK_INT >= 11) {
//--post GB use serial executor by default --
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
//--GB uses ThreadPoolExecutor by default--
task.execute();
}
只是...使用
new YourAssynctask().execute();
这确实会调用您的 Assyntask 的 OnpreExecute() 方法。
创建异步任务的新实例并执行,然后它将并行执行
AsyncTask 使用线程池模式来运行来自 doInBackground() 的内容。问题最初是(在早期的 Android 操作系统版本中)池大小仅为 1,这意味着一堆 AsyncTask 没有并行计算。但后来他们修复了这个问题,现在大小是 5。
new myAsync().execute(params);
new myAsync().execute(params);