1.asyncTask在android开发中,使用频率还是挺高,asyncTask是coogle官方提供的api,在android 3.0之后coogle对asyncTask进行了一次修改,android 3.0之前asyncTask用的线程池是并发线程池,android 3.0之后coogle官方对asyncTask并发线程池做了一些控制,在AsyncTask类里面用到一个静态内部类SerialExecutor
private static class SerialExecutor implements Executor { //SerialExecutor是一个静态类,不会随着AsyncTask的创建而存在多个, final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); Runnable mActive; public synchronized void execute(final Runnable r) { //AsyncTask要执行任务会通过这个方法放入数组队列 mTasks.offer(new Runnable() { //将任务放入数组队列 public void run() { try { r.run();//注:在子线程中调用future的run方法,也就保证future的run方法执行在子线, } finally { scheduleNext();//从代码可以看出,只有上面的run方法执行完,sheduleNext才有去执行,也就保证AsynTask是任务,保证了依次去执行队列的任务,这里有个疑问,在子线程吃去执行执行线程池,会有什么影响吗 } } }); if (mActive == null) {//第一次执行任务时,mAtive才为null,后面再次执行任务,mActive不空scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { //从数组队列中取出消息 THREAD_POOL_EXECUTOR.execute(mActive); } } }
从上面的代码是android 3.0以后的实现,android 3.0之前是直接sheduleNext方法里面的THTREAD_POOL_EXECUTOR并发线程池去执行,具体去android 3.0的AsyncTask看源码。
2.Android3.0之后改成这样,有利也有弊,如果用户需要去多任务去下载图片,AsyncTask默认线程池就不适用了,我们可以对AsyncTask的默认线程池进行修改,AsyncTask也提供的接口,让我们可以灵活的使用控制AysncTask的线程池
/** @hide */ public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; }
我们可以通过这个方法去修改AsyncTask里面的默认线程池,默认线程池也是上面我们介绍过的SerialExecutor
3,下面介绍下AsyncTask怎样去在子线程运行完后去更新UI的
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { //这个方法是在AsyncTask执行execute执行后执行的方法 if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); //在执行线程前 我们可以重写这个方法在线程执行前弹出加载dialog mWorker.mParams = params; exec.execute(mFuture);、江将一个future执行mfuturefutrueure是是是runRunnale的子类, return this; }
mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked return postResult(doInBackground(mParams)); //在子线程执行doInBackground方法,我们要做一些耗时的工作,在doInBackground去里面做 } }; mFuture = new FutureTask<Result>(mWorker) { //在run方法通过调用WorkerRunnable的call方法 @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; }.....private Result postResult(Result result) { //将子线程的返回的结果,同handle去更新UI @SuppressWarnings("unchecked") Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; }...private static class InternalHandler extends Handler { public InternalHandler() { super(Looper.getMainLooper()); } @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } }private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result);//我们可以通过重写这个方法拿到子线程返回结果,去更新ui } mStatus = Status.FINISHED; }