1. AsyncTask 一次只能执行一个任务,太耗时的操作不能用AsyncTask。AsyncTasks should ideally be used for short operations (a few seconds at the most.)
曾经在工作中遇到一个问题,一个程序里面创建了多个AsyncTask,其中两个一个是下载图片,另一个是录音。当录音开启时候,下载图片,图片一直无法下载。从源码看是这样的:
private static class SerialExecutor implements Executor { final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); Runnable mActive; public synchronized void execute(final Runnable r) { mTasks.offer(new Runnable() { public void run() { // 这里只是将线程装到线程池里,并没有执行。 try { r.run(); // 只有当前的线程执行完后才能继续下一个任务。 } finally { scheduleNext(); } } }); if (mActive == null) { // 当第一个线程过来的时候,mActive==null满足条件. // 执行下面的方法调到THREAD_POOL_EXECUTOR.execute(mActive); // 最终会调到上面的run(). scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } }
2. 什么时候用AsyncTask,什么时候用thread?
AsyncTask只适用于短时间(小于3S)的操作,具体原因见上;使用AsyncTask必须与UI有交互。
而Thread没有这些限制。