代码改变世界

AsyncTask原理

2013-05-24 13:52  和尚释然  阅读(448)  评论(0编辑  收藏  举报

AsyncTask的基本原理是创建一个线程池,通过线程池执行一个Runnable对象(FutureTask),然后通过Handler通知UI线程。

1、线程池的创建。创建线程池,并返回一个执行器对象(Executor)

[java] viewplaincopy

  1. private static final int CORE_POOL_SIZE = 5;
  2. private static final int MAXIMUM_POOL_SIZE = 128;
  3. private static final int KEEP_ALIVE = 10;
  4. private static final BlockingQueue<Runnable> sWorkQueue =
  5. new LinkedBlockingQueue<Runnable>(10);
  6. private static final ThreadFactory sThreadFactory = new ThreadFactory() {
  7. private final AtomicInteger mCount = new AtomicInteger(1);
  8. public Thread newThread(Runnable r) {
  9. return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
  10. }
  11. };
  12. private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
  13. MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);

2、将被执行的Runnable对象(FutureTask)的创建。在构造方法中创建FutureTask。

[java] viewplaincopy

  1. public AsyncTask() {
  2. mWorker = new WorkerRunnable<Params, Result>() {
  3. public Result call() throws Exception {
  4. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
  5. return doInBackground(mParams);
  6. }
  7. };
  8. mFuture = new FutureTask<Result>(mWorker) {
  9. @Override
  10. protected void done() {
  11. Message message;
  12. Result result = null;
  13. try {
  14. result = get();
  15. } catch (InterruptedException e) {
  16. android.util.Log.w(LOG_TAG, e);
  17. } catch (ExecutionException e) {
  18. throw new RuntimeException("An error occured while executing doInBackground()",
  19. e.getCause());
  20. } catch (CancellationException e) {
  21. <span style="color:#ff0000;"> </span>message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
  22. new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
  23. message.sendToTarget();
  24. return;
  25. } catch (Throwable t) {
  26. throw new RuntimeException("An error occured while executing "
  27. + "doInBackground()", t);
  28. }
  29. message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
  30. new AsyncTaskResult<Result>(AsyncTask.this, result));
  31. message.sendToTarget();
  32. }
  33. };
  34. }

其中WorkRunnable是一个Callable对象:

[java] viewplaincopy

  1. private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
  2. Params[] mParams;
  3. }

3、执行,execute方法。

[html] viewplaincopy

  1. public final AsyncTask<Params, Progress, Result> execute(Params... params) {
  2. if (mStatus != Status.PENDING) {
  3. switch (mStatus) {
  4. case RUNNING:
  5. throw new IllegalStateException("Cannot execute task:"
  6. + " the task is already running.");
  7. case FINISHED:
  8. throw new IllegalStateException("Cannot execute task:"
  9. + " the task has already been executed "
  10. + "(a task can be executed only once)");
  11. }
  12. }
  13. mStatus = Status.RUNNING;
  14. onPreExecute();
  15. mWorker.mParams = params;
  16. sExecutor.execute(mFuture);
  17. return this;
  18. }

4、使用Handler通知UI线程,在上面的第二步中最后两行代码。