AsyncTask运行在单线程下

    在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的同学还真是得细心才行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值