在Android中使用多线程,首先考虑的就是AsyncTask,原因不用多少,方便。但是今天在做项目的时候发现一个问题,我在一个Service中启动了2个AsyncTask分别执行不同的任务,但却只有一个在运行,怎么回事呢?
首先想到的是可能Service限制了线程数量,写了2个Thread并行运行发现没问题,然后就想到可能是AsyncTask的问题,上官网查了下发现如下描述:
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 with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by
parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
原来Android1.6以后更新让AsyncTask获得了并行的能力,但是为了避免因为并行引起的大部分应用程序错误自3.0开始让所有AsyncTask运行在一个单独的线程中,也就是说所有的AsyncTask是串行的!!不过不用急,Google说如果你真的想要使AsyncTask并行,可以使用:
executeOnExecutor(java.util.concurrent.Executor, Object[])
参数传入一个线程池即可,如:
ExecutorService pool = Executors.newCachedThreadPool();
做Android的同学还真是得细心才行。