Asynctask解析以及注意事项

来源:互联网 发布:什么是炒黄金知乎 编辑:程序博客网 时间:2024/05/17 08:29
[java] view plaincopy
  1. /* 
  2.     说到AsyncTask这个类,好多人其实不太了解。最近看了下代码,把心得分享给大家。 
  3.     AsyncTask的execute的执行流程为 
  4.     先调用ThreadPoolExecutor.execute(mFuture); 
  5.     然后ThreadPoolExecutor.execute(mFuture) 会调用ThreadPoolExecutor.addWorker(mFuture); 
  6.     最后ThreadPoolExecutor.addWorker(mFuture)会调用mFuture的run()方法,run方法中就是该线程要执行操作的地方 
  7.     到此我们来关注一下mFuture,AsyncTask中的mFuture是一个FutureTask,FutureTask实现了Future<V>, Runnable两个接口, 
  8.     Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果,计算完成后只能使用 get 方法来获取结果。 
  9.     mFuture以mWorker作为参数 
  10.     现看mFuture的构造方法: 
  11. public void run() { 
  12.     sync.innerRun(); 
  13. } 
  14.  
  15.     sync是什么呢?Sync类是一个内部类,我们看看它的初始化 
  16. public FutureTask(Callable<V> callable) { 
  17.     if (callable == null) 
  18.         throw new NullPointerException(); 
  19.     sync = new Sync(callable); 
  20. } 
  21.     在看看sync.innerRun()方法: 
  22. void innerRun() { 
  23.     if (!compareAndSetState(READY, RUNNING)) 
  24.         return; 
  25.  
  26.     runner = Thread.currentThread(); 
  27.     if (getState() == RUNNING) { // recheck after setting thread 
  28.         V result; 
  29.         try { 
  30.             result = callable.call(); 
  31.         } catch (Throwable ex) { 
  32.             setException(ex); 
  33.             return; 
  34.         } 
  35.         set(result); 
  36.     } else { 
  37.         releaseShared(0); // cancel 
  38.     } 
  39. } 
  40.     从代码可以看到,其实最终是调用了callable.call()这个方法。 
  41.     从AsyncTask中我们可以知道,我们传入的Callable是我们的WorkerRunnable 
  42.     所以,我们会调用WorkerRunnable的call()方法,在call方法里面 
  43.     返回postResult(doInBackground(mParams)); 
  44.     通知UI线程更新,这就是调用过程 
  45. Notes: 
  46. 1: 
  47.     因为AsyncTask里面的内部handler和Executor都是静态变量,所以,他们控制着所有的子类。 
  48. 2: 
  49.     我们可以通过AsyncTask.execute()方法来调用系统默认的线程池来处理当前的任务, 
  50.     系统默认的线程池用的是SerialExecutor.这个线程池控制所有任务按顺序执行。也就是一次只执行一条. 
  51.     当前执行完了,才执行下一条.2.3平台以前是所有的任务并发执行,这会导致一种情况,就是其中一条任务执行出问题了,会引起其他任务 
  52.     出现错误. 
  53. 3: 
  54.     AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)你也可以采用这个系统提供的线程池来处理你的任务 
  55.     默认这个线程池是并发处理任务的,也就是不按顺序来.核心为5条,最大128条 
  56. 4: 
  57.     你也可以使用自定义的线程池,这样就可以即使的执行你的任务需求,而不是用系统的。因为用系统默认的线程池可以需要等待,它默认 
  58.     是按顺序执行(THREAD_POOL_EXECUTOR)或者最多执行5个(SerialExecutor). 
  59.     自己使用自定义线程池方式如下: 
  60.     new AsyncTask.executeOnExecutor((ExecutorService)Executors.newCachedThreadPool()). 
  61. 5:  不要随意使用AsyncTask,除非你必须要与UI线程交互.默认情况下使用Thread即可,要注意需要将线程优先级调低. 
  62.     从google官方文档你也可以看到,AsyncTasks should ideally be used for short operations (a few seconds at the most.) 
  63.     AsyncTask适合处理短时间的操作,长时间的操作,比如下载一个很大的视频,这就需要你使用自己的线程来下载,不管是断点下载还是其它的. 
  64.     当然,如果你需要开启自定义的很多线程来处理你的任务,切记你此时可以考虑自定义线程池 
  65.  */   
  66. public abstract class AsyncTask<Params, Progress, Result> {  
  67.     private static final String LOG_TAG = "AsyncTask";  
  68.     // 核心线程数是要  
  69.     private static final int CORE_POOL_SIZE = 5;  
  70.     // 最大线程数支持128  
  71.     private static final int MAXIMUM_POOL_SIZE = 128;  
  72.     // 这个参数的的意思是当前线程池里面的thread如果超过了规定的核心线程5,如果有线程的空闲时间超过了这个数值,  
  73.     // 数值的单位自己指定,就回收该线程的资源,达到动态调整线程池资源的目的.  
  74.     private static final int KEEP_ALIVE = 1;  
  75.     // ThreadFactory是用来在线程池中构建新线程的方法.可以看到每次构建一个方法,名字都不同.为"AsyncTask # 1++".  
  76.     private static final ThreadFactory sThreadFactory = new ThreadFactory() {  
  77.         private final AtomicInteger mCount = new AtomicInteger(1);  
  78.   
  79.         public Thread newThread(Runnable r) {  
  80.             return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());  
  81.         }  
  82.     };  
  83.     // 线程池所使用的缓冲队列.FIFO,它用于存放如果当前线程池中核心线程已满,此时来的任务都被放到缓冲队列中等待被处理.  
  84.     // 初始化容量为10  
  85.     private static final BlockingQueue<Runnable> sPoolWorkQueue =  
  86.             new LinkedBlockingQueue<Runnable>(10);  
  87.   
  88.     /** 
  89.      * An {@link Executor} that can be used to execute tasks in parallel. 
  90.      */  
  91.     // 线程池的初始化,指定了核心线程5,最大线程128,超时1s,缓冲队列等, 你在使用asyncTask的时候,可以传入这个参数,  
  92.     // 就可以让多条线程并发的执行了.比如:executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)  
  93.     public static final Executor THREAD_POOL_EXECUTOR  
  94.             = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,  
  95.                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);  
  96.   
  97.     /** 
  98.      * An {@link Executor} that executes tasks one at a time in serial 
  99.      * order.  This serialization is global to a particular process. 
  100.      */  
  101.     // 从这个线程池内部看,已经不是并行执行任务,而是一次只执行一个.  
  102.     public static final Executor SERIAL_EXECUTOR = new SerialExecutor();  
  103.     // 消息数值  
  104.     private static final int MESSAGE_POST_RESULT = 0x1;  
  105.     private static final int MESSAGE_POST_PROGRESS = 0x2;  
  106.     // 这个InternalHandler就是用来是UI线程打交道的。可以看到它是个静态的变量。也就是说谁第一次调用它,下一次另一个  
  107.     // 线程来调用,也不会实例话这个常量.关于这个handler,默认asynctask都是从主线程中调用的,所以,这个Handler默认  
  108.     // 获得了主线程的Looper,所以就能和主线程来交互. Notes:假如你在一个子线程中构建了自己的Looper并使用Asynctask,  
  109.     // 应该会出问题,因为此时这个Handler就属于子线程了,就不能去操控UI的操作.这应该算是AsyncTask的Bug.网上有人说  
  110.     // 在4.0上运行没问题,2.3会有问题,原因是因为4.0中的ActivityThread.main方法里面最先用主线程的Looper来初始化了这个  
  111.     // AsyncTask。理论上Asynctask应该判断当前的Looper如果不是MainThread的Looper的话,抛出异常,遗憾的是,  
  112.     // google没有考虑到这里,只是在文档中要求必须在主线程中调用,其实,很不好!  
  113.     private static final InternalHandler sHandler = new InternalHandler();  
  114.   
  115.     private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;  
  116.     // 自定义的静态内部类  
  117.     private final WorkerRunnable<Params, Result> mWorker;  
  118.     // 其实就是也一个Runnable,实现了这个接口  
  119.     private final FutureTask<Result> mFuture;  
  120.   
  121.     // 默认为pending状态。  
  122.     private volatile Status mStatus = Status.PENDING;  
  123.     // 原子操作,专门用来处理并发访问,就可以不用synchronized  
  124.     private final AtomicBoolean mCancelled = new AtomicBoolean();  
  125.     private final AtomicBoolean mTaskInvoked = new AtomicBoolean();  
  126.   
  127.     private static class SerialExecutor implements Executor {  
  128.         // ArrayDeque是一个双向队列,我们来理解下这个线程池是如何做到一次只  
  129.         // 执行一条任务的.比如此时有多处先后都调用了AsyncTask.execute()方法,  
  130.         // 对第一条最先到的任务来说,首先自己被假如到了队列中,因为第一次mActive == null成立,  
  131.         // 所以执行THREAD_POOL_EXECUTOR.execute(mActive).且mActive 此时不等于Null.  
  132.         // 所以第二条任务来的时候,只是被加入到了队列中,并不会执行.除非第一条任务执行完了,在它的finnally方法中  
  133.         // 调用scheduleNext()去再次从对列中取出下一条任务来执行.这样就实现了所有任务按顺序执行的功能.  
  134.         final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();  
  135.         Runnable mActive;  
  136.   
  137.         public synchronized void execute(final Runnable r) {  
  138.             // 把线程offer到队列中  
  139.             mTasks.offer(new Runnable() {  
  140.                 public void run() {  
  141.                     try {  
  142.                         r.run();  
  143.                     } finally {  
  144.                         // 一条执行完了,执行下一条任务  
  145.                         scheduleNext();  
  146.                     }  
  147.                 }  
  148.             });  
  149.             if (mActive == null) {  
  150.                 scheduleNext();  
  151.             }  
  152.         }  
  153.   
  154.         protected synchronized void scheduleNext() {  
  155.             if ((mActive = mTasks.poll()) != null) {  
  156.                 THREAD_POOL_EXECUTOR.execute(mActive);  
  157.             }  
  158.         }  
  159.     }  
  160.   
  161.     /** 
  162.      * Indicates the current status of the task. Each status will be set only once 
  163.      * during the lifetime of a task. 
  164.      */  
  165.     public enum Status {  
  166.         /** 
  167.          * Indicates that the task has not been executed yet. 
  168.          */  
  169.         PENDING,  
  170.         /** 
  171.          * Indicates that the task is running. 
  172.          */  
  173.         RUNNING,  
  174.         /** 
  175.          * Indicates that {@link AsyncTask#onPostExecute} has finished. 
  176.          */  
  177.         FINISHED,  
  178.     }  
  179.   
  180.     /** @hide Used to force static handler to be created. */  
  181.     public static void init() {  
  182.         sHandler.getLooper();  
  183.     }  
  184.   
  185.     /** @hide */  
  186.     public static void setDefaultExecutor(Executor exec) {  
  187.         sDefaultExecutor = exec;  
  188.     }  
  189.   
  190.     /** 
  191.      * Creates a new asynchronous task. This constructor must be invoked on the UI thread. 
  192.      */  
  193.     public AsyncTask() {  
  194.         //初始化mWorker并复写call方法,后面会介绍什么时候调用  
  195.         mWorker = new WorkerRunnable<Params, Result>() {  
  196.             // 这个方法就是当你嗲用excutor.excute()方法后执行的方法。至于是如何执行的,我们后面会分析  
  197.             public Result call() throws Exception {  
  198.                 mTaskInvoked.set(true);  
  199.                 // 将线程优先级设置为后台线程,默认和主线程优先级一样,如果不这样做,也会降低程序性能.因为会优先  
  200.                 // 抢占cpu资源.所以,如果你在程序中不使用asyncTask而是自己new 一条线程出来,记得把线程的优先级设置为  
  201.                 // 后台线程  
  202.                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  203.                 //这个地方调用了我们自己实现的doInBackground  
  204.                 return postResult(doInBackground(mParams));  
  205.             }  
  206.         };  
  207.        // 用mWorker创建一个可取消的异步计算任务  
  208.         mFuture = new FutureTask<Result>(mWorker) {  
  209.             @Override  
  210.             // 当任务不管是正常终止、异常或取消而完成的,都回调此方法, 即isDone()为true时,isDone不管成功还是失败都  
  211.             // 返回true  
  212.             protected void done() {  
  213.                 try {  
  214.                     // 如果当前的task没有被invoke,就被finish掉  
  215.                     postResultIfNotInvoked(get());  
  216.                 } catch (InterruptedException e) {  
  217.                     android.util.Log.w(LOG_TAG, e);  
  218.                 } catch (ExecutionException e) {  
  219.                     throw new RuntimeException("An error occured while executing doInBackground()",  
  220.                             e.getCause());  
  221.                 } catch (CancellationException e) {  
  222.                     postResultIfNotInvoked(null);  
  223.                 }  
  224.             }  
  225.         };  
  226.     }  
  227.   
  228.     private void postResultIfNotInvoked(Result result) {  
  229.         final boolean wasTaskInvoked = mTaskInvoked.get();  
  230.         if (!wasTaskInvoked) {  
  231.             postResult(result);  
  232.         }  
  233.     }  
  234.   
  235.     // 当doInBackground结束了,调用PostResult发布结果  
  236.     private Result postResult(Result result) {  
  237.         @SuppressWarnings("unchecked")  
  238.         Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,  
  239.                 new AsyncTaskResult<Result>(this, result));  
  240.         message.sendToTarget();  
  241.         return result;  
  242.     }  
  243.   
  244.     /** 
  245.      * Returns the current status of this task. 
  246.      * 
  247.      * @return The current status. 
  248.      */  
  249.     // 获得当前的状态  
  250.     public final Status getStatus() {  
  251.         return mStatus;  
  252.     }  
  253.   
  254.     /** 
  255.      * Override this method to perform a computation on a background thread. The 
  256.      * specified parameters are the parameters passed to {@link #execute} 
  257.      * by the caller of this task. 
  258.      * 
  259.      * This method can call {@link #publishProgress} to publish updates 
  260.      * on the UI thread. 
  261.      * 
  262.      * @param params The parameters of the task. 
  263.      * 
  264.      * @return A result, defined by the subclass of this task. 
  265.      * 
  266.      * @see #onPreExecute() 
  267.      * @see #onPostExecute 
  268.      * @see #publishProgress 
  269.      */  
  270.     // 用户自己实现  
  271.     protected abstract Result doInBackground(Params... params);  
  272.   
  273.     /** 
  274.      * Runs on the UI thread before {@link #doInBackground}. 
  275.      * 
  276.      * @see #onPostExecute 
  277.      * @see #doInBackground 
  278.      */  
  279.     // 用户自己实现  
  280.     protected void onPreExecute() {  
  281.     }  
  282.   
  283.     /** 
  284.      * <p>Runs on the UI thread after {@link #doInBackground}. The 
  285.      * specified result is the value returned by {@link #doInBackground}.</p> 
  286.      * 
  287.      * <p>This method won't be invoked if the task was cancelled.</p> 
  288.      * 
  289.      * @param result The result of the operation computed by {@link #doInBackground}. 
  290.      * 
  291.      * @see #onPreExecute 
  292.      * @see #doInBackground 
  293.      * @see #onCancelled(Object) 
  294.      */  
  295.     @SuppressWarnings({"UnusedDeclaration"})  
  296.     // 用户自己实现  
  297.     protected void onPostExecute(Result result) {  
  298.     }  
  299.   
  300.     /** 
  301.      * Runs on the UI thread after {@link #publishProgress} is invoked. 
  302.      * The specified values are the values passed to {@link #publishProgress}. 
  303.      * 
  304.      * @param values The values indicating progress. 
  305.      * 
  306.      * @see #publishProgress 
  307.      * @see #doInBackground 
  308.      */  
  309.     @SuppressWarnings({"UnusedDeclaration"})  
  310.     // 用户自己实现  
  311.     protected void onProgressUpdate(Progress... values) {  
  312.     }  
  313.   
  314.     /** 
  315.      * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and 
  316.      * {@link #doInBackground(Object[])} has finished.</p> 
  317.      * 
  318.      * <p>The default implementation simply invokes {@link #onCancelled()} and 
  319.      * ignores the result. If you write your own implementation, do not call 
  320.      * <code>super.onCancelled(result)</code>.</p> 
  321.      * 
  322.      * @param result The result, if any, computed in 
  323.      *               {@link #doInBackground(Object[])}, can be null 
  324.      * 
  325.      * @see #cancel(boolean) 
  326.      * @see #isCancelled() 
  327.      */  
  328.     @SuppressWarnings({"UnusedParameters"})  
  329.     protected void onCancelled(Result result) {  
  330.         onCancelled();  
  331.     }  
  332.   
  333.     /** 
  334.      * <p>Applications should preferably override {@link #onCancelled(Object)}. 
  335.      * This method is invoked by the default implementation of 
  336.      * {@link #onCancelled(Object)}.</p> 
  337.      * 
  338.      * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and 
  339.      * {@link #doInBackground(Object[])} has finished.</p> 
  340.      * 
  341.      * @see #onCancelled(Object) 
  342.      * @see #cancel(boolean) 
  343.      * @see #isCancelled() 
  344.      */  
  345.     protected void onCancelled() {  
  346.     }  
  347.   
  348.     /** 
  349.      * Returns <tt>true</tt> if this task was cancelled before it completed 
  350.      * normally. If you are calling {@link #cancel(boolean)} on the task, 
  351.      * the value returned by this method should be checked periodically from 
  352.      * {@link #doInBackground(Object[])} to end the task as soon as possible. 
  353.      * 
  354.      * @return <tt>true</tt> if task was cancelled before it completed 
  355.      * 
  356.      * @see #cancel(boolean) 
  357.      */  
  358.     public final boolean isCancelled() {  
  359.         return mCancelled.get();  
  360.     }  
  361.   
  362.     /** 
  363.      * <p>Attempts to cancel execution of this task.  This attempt will 
  364.      * fail if the task has already completed, already been cancelled, 
  365.      * or could not be cancelled for some other reason. If successful, 
  366.      * and this task has not started when <tt>cancel</tt> is called, 
  367.      * this task should never run. If the task has already started, 
  368.      * then the <tt>mayInterruptIfRunning</tt> parameter determines 
  369.      * whether the thread executing this task should be interrupted in 
  370.      * an attempt to stop the task.</p> 
  371.      * 
  372.      * <p>Calling this method will result in {@link #onCancelled(Object)} being 
  373.      * invoked on the UI thread after {@link #doInBackground(Object[])} 
  374.      * returns. Calling this method guarantees that {@link #onPostExecute(Object)} 
  375.      * is never invoked. After invoking this method, you should check the 
  376.      * value returned by {@link #isCancelled()} periodically from 
  377.      * {@link #doInBackground(Object[])} to finish the task as early as 
  378.      * possible.</p> 
  379.      * 
  380.      * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this 
  381.      *        task should be interrupted; otherwise, in-progress tasks are allowed 
  382.      *        to complete. 
  383.      * 
  384.      * @return <tt>false</tt> if the task could not be cancelled, 
  385.      *         typically because it has already completed normally; 
  386.      *         <tt>true</tt> otherwise 
  387.      * 
  388.      * @see #isCancelled() 
  389.      * @see #onCancelled(Object) 
  390.      */  
  391.     public final boolean cancel(boolean mayInterruptIfRunning) {  
  392.         mCancelled.set(true);  
  393.         return mFuture.cancel(mayInterruptIfRunning);  
  394.     }  
  395.   
  396.     /** 
  397.      * Waits if necessary for the computation to complete, and then 
  398.      * retrieves its result. 
  399.      * 
  400.      * @return The computed result. 
  401.      * 
  402.      * @throws CancellationException If the computation was cancelled. 
  403.      * @throws ExecutionException If the computation threw an exception. 
  404.      * @throws InterruptedException If the current thread was interrupted 
  405.      *         while waiting. 
  406.      */  
  407.     public final Result get() throws InterruptedException, ExecutionException {  
  408.         return mFuture.get();  
  409.     }  
  410.   
  411.     /** 
  412.      * Waits if necessary for at most the given time for the computation 
  413.      * to complete, and then retrieves its result. 
  414.      * 
  415.      * @param timeout Time to wait before cancelling the operation. 
  416.      * @param unit The time unit for the timeout. 
  417.      * 
  418.      * @return The computed result. 
  419.      * 
  420.      * @throws CancellationException If the computation was cancelled. 
  421.      * @throws ExecutionException If the computation threw an exception. 
  422.      * @throws InterruptedException If the current thread was interrupted 
  423.      *         while waiting. 
  424.      * @throws TimeoutException If the wait timed out. 
  425.      */  
  426.     public final Result get(long timeout, TimeUnit unit) throws InterruptedException,  
  427.             ExecutionException, TimeoutException {  
  428.         return mFuture.get(timeout, unit);  
  429.     }  
  430.   
  431.     /** 
  432.      * Executes the task with the specified parameters. The task returns 
  433.      * itself (this) so that the caller can keep a reference to it. 
  434.      * 
  435.      * <p>Note: this function schedules the task on a queue for a single background 
  436.      * thread or pool of threads depending on the platform version.  When first 
  437.      * introduced, AsyncTasks were executed serially on a single background thread. 
  438.      * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed 
  439.      * to a pool of threads allowing multiple tasks to operate in parallel. Starting 
  440.      * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being 
  441.      * executed on a single thread to avoid common application errors caused 
  442.      * by parallel execution.  If you truly want parallel execution, you can use 
  443.      * the {@link #executeOnExecutor} version of this method 
  444.      * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings 
  445.      * on its use. 
  446.      * 
  447.      * <p>This method must be invoked on the UI thread. 
  448.      * 
  449.      * @param params The parameters of the task. 
  450.      * 
  451.      * @return This instance of AsyncTask. 
  452.      * 
  453.      * @throws IllegalStateException If {@link #getStatus()} returns either 
  454.      *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. 
  455.      * 
  456.      * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) 
  457.      * @see #execute(Runnable) 
  458.      */  
  459.     // 这个方法就是用户调用的excute方法,默认采用asynctask自带的线程池串行执行任务  
  460.     public final AsyncTask<Params, Progress, Result> execute(Params... params) {  
  461.         return executeOnExecutor(sDefaultExecutor, params);  
  462.     }  
  463.   
  464.     /** 
  465.      * Executes the task with the specified parameters. The task returns 
  466.      * itself (this) so that the caller can keep a reference to it. 
  467.      * 
  468.      * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to 
  469.      * allow multiple tasks to run in parallel on a pool of threads managed by 
  470.      * AsyncTask, however you can also use your own {@link Executor} for custom 
  471.      * behavior. 
  472.      * 
  473.      * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from 
  474.      * a thread pool is generally <em>not</em> what one wants, because the order 
  475.      * of their operation is not defined.  For example, if these tasks are used 
  476.      * to modify any state in common (such as writing a file due to a button click), 
  477.      * there are no guarantees on the order of the modifications. 
  478.      * Without careful work it is possible in rare cases for the newer version 
  479.      * of the data to be over-written by an older one, leading to obscure data 
  480.      * loss and stability issues.  Such changes are best 
  481.      * executed in serial; to guarantee such work is serialized regardless of 
  482.      * platform version you can use this function with {@link #SERIAL_EXECUTOR}. 
  483.      * 
  484.      * <p>This method must be invoked on the UI thread. 
  485.      * 
  486.      * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a 
  487.      *              convenient process-wide thread pool for tasks that are loosely coupled. 
  488.      * @param params The parameters of the task. 
  489.      * 
  490.      * @return This instance of AsyncTask. 
  491.      * 
  492.      * @throws IllegalStateException If {@link #getStatus()} returns either 
  493.      *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. 
  494.      * 
  495.      * @see #execute(Object[]) 
  496.      */  
  497.     public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,  
  498.             Params... params) {  
  499.         // 可以看出同一个任务只能执行一次  
  500.         if (mStatus != Status.PENDING) {  
  501.             switch (mStatus) {  
  502.                 case RUNNING:  
  503.                     throw new IllegalStateException("Cannot execute task:"  
  504.                             + " the task is already running.");  
  505.                 case FINISHED:  
  506.                     throw new IllegalStateException("Cannot execute task:"  
  507.                             + " the task has already been executed "  
  508.                             + "(a task can be executed only once)");  
  509.             }  
  510.         }  
  511.   
  512.         mStatus = Status.RUNNING;  
  513.         // 调用用户--UI线程---自己实现的方法  
  514.         onPreExecute();  
  515.   
  516.         mWorker.mParams = params;  
  517.         // 这个方法就会调用前面的mWorker的call方法  
  518.         exec.execute(mFuture);  
  519.   
  520.         return this;  
  521.     }  
  522.   
  523.     /** 
  524.      * Convenience version of {@link #execute(Object...)} for use with 
  525.      * a simple Runnable object. See {@link #execute(Object[])} for more 
  526.      * information on the order of execution. 
  527.      * 
  528.      * @see #execute(Object[]) 
  529.      * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) 
  530.      */  
  531.     public static void execute(Runnable runnable) {  
  532.         sDefaultExecutor.execute(runnable);  
  533.     }  
  534.   
  535.     /** 
  536.      * This method can be invoked from {@link #doInBackground} to 
  537.      * publish updates on the UI thread while the background computation is 
  538.      * still running. Each call to this method will trigger the execution of 
  539.      * {@link #onProgressUpdate} on the UI thread. 
  540.      * 
  541.      * {@link #onProgressUpdate} will note be called if the task has been 
  542.      * canceled. 
  543.      * 
  544.      * @param values The progress values to update the UI with. 
  545.      * 
  546.      * @see #onProgressUpdate 
  547.      * @see #doInBackground 
  548.      */  
  549.     protected final void publishProgress(Progress... values) {  
  550.         if (!isCancelled()) {  
  551.             sHandler.obtainMessage(MESSAGE_POST_PROGRESS,  
  552.                     new AsyncTaskResult<Progress>(this, values)).sendToTarget();  
  553.         }  
  554.     }  
  555.   
  556.     private void finish(Result result) {  
  557.         if (isCancelled()) {  
  558.             onCancelled(result);  
  559.         } else {  
  560.             onPostExecute(result);  
  561.         }  
  562.         mStatus = Status.FINISHED;  
  563.     }  
  564.   
  565.     //  与UI交互  
  566.     private static class InternalHandler extends Handler {  
  567.         @SuppressWarnings({"unchecked""RawUseOfParameterizedType"})  
  568.         @Override  
  569.         public void handleMessage(Message msg) {  
  570.             AsyncTaskResult result = (AsyncTaskResult) msg.obj;  
  571.             switch (msg.what) {  
  572.                 case MESSAGE_POST_RESULT:  
  573.                     // There is only one result  
  574.                     result.mTask.finish(result.mData[0]);  
  575.                     break;  
  576.                 case MESSAGE_POST_PROGRESS:  
  577.                     result.mTask.onProgressUpdate(result.mData);  
  578.                     break;  
  579.             }  
  580.         }  
  581.     }  
  582.   
  583.     private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {  
  584.         Params[] mParams;  
  585.     }  
  586.   
  587.     @SuppressWarnings({"RawUseOfParameterizedType"})  
  588.     // 存储异步执行结果的类  
  589.     private static class AsyncTaskResult<Data> {  
  590.         final AsyncTask mTask;  
  591.         final Data[] mData;  
  592.   
  593.         AsyncTaskResult(AsyncTask task, Data... data) {  
  594.             mTask = task;  
  595.             mData = data;  
  596.         }  
  597.     }  
  598. }  

原创粉丝点击