线程间通讯机制(提高篇)——深入浅出实现原理

前言:

这一篇博文主要是和大家讲解一下线程间通讯机制的内部实现原理,即Handler、Message、MessageQueue、Looper、HandlerThread、AsyncTask类的实现以及之间的关系。如果还没有接触过Handler+Message+Runnable、HandlerThread、AsyncTask的朋友可以先看看基础篇:


【Android开发】线程间通讯机制(基础篇)——Handler、Runnable、HandlerThread、AsyncTask的使用


有时候,如果你能带着问题或者目标去探索新知识的话,这样的学习效率就高很多。所以我们先从最基础的实现方式(Handler+Message+Runnable)说起。


一、Handler+Message+Runnable内部解析

问题:我们在使用Handler类的时候,都知道有sendMessage(Message)等发送消息的功能和post(Runnable)发送任务的功能,然后还有能够处理接受到的Message的功能。这时候我就会提出这样的问题:

1、有发送、接受Message的功能,是不是sendMessage方法是直接调用handleMessage的重写方法里呢?

2、不是有按时间计划发送Message和Runnable吗?如果问题1成立的话,handleMessage可能会同时接受多个Message,但是此方法不是线程安全的(没有synchronized修饰),这样会出现问题了。

    

解决问题:如果对API有任何疑惑,最根本的方法就是查看源代码。

在看源代码之前,需要了解几个类:

Handler:负责发送Message和Runnable到MessageQueue中,然后依次处理MessageQueue里面的队列。

MessageQueue:消息队列。负责存放一个线程的Message和Runnable的集合。

Message:消息实体类。

Looper:消息循环器。负责把MessageQueue中的Message或者Runnable循环取出来,然后分发到Handler中。


四者的关系:一个线程可以有多个Handler实例,一个线程对应一个Looper,一个Looper也只对应一个MessageQueue,一个MessageQueue对应多个Message和Runnable。所以就形成了一对多的对应关系,一方:线程、Looper、MessageQueue;多方:Handler、Message。同时可以看出另一个一对一关系:一个Message实例对应一个Handler实例。


一个Handler实例都会与一个线程和消息队列捆绑在一起,当实例化Handler的时候,就已经完成这样的工作。源码如下:

Handler类

  1. /** 
  2.      * Default constructor associates this handler with the {@link Looper} for the 
  3.      * current thread. 
  4.      * 
  5.      * If this thread does not have a looper, this handler won't be able to receive messages 
  6.      * so an exception is thrown. 
  7.      */  
  8.     public Handler() {  
  9.         this(nullfalse);  
  10.     }  

  1. public Handler(Callback callback, boolean async) {  
  2.         if (FIND_POTENTIAL_LEAKS) {  
  3.             final Class<? extends Handler> klass = getClass();  
  4.             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&  
  5.                     (klass.getModifiers() & Modifier.STATIC) == 0) {  
  6.                 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +  
  7.                     klass.getCanonicalName());  
  8.             }  
  9.         }  
  10.   
  11.         mLooper = Looper.myLooper();  
  12.         if (mLooper == null) {  
  13.             throw new RuntimeException(  
  14.                 "Can't create handler inside thread that has not called Looper.prepare()");  
  15.         }  
  16.         mQueue = mLooper.mQueue;  
  17.         mCallback = callback;  
  18.         mAsynchronous = async;  
  19.     }  

  可以从mLooper = Looper.myLooper()

mQueue = mLooper.mQueue;看出,实例化Handler就会绑定一个Looper实例,并且一个Looper实例包涵一个MessageQueue实例。

问题来了,为什么说一个线程对应一个Looper实例?我们通过Looper.myLooper()找原因:

Looper类

  1. // sThreadLocal.get() will return null unless you've called prepare().  
  2.    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();  

  1. /** 
  2.      * Return the Looper object associated with the current thread.  Returns 
  3.      * null if the calling thread is not associated with a Looper. 
  4.      */  
  5.     public static Looper myLooper() {  
  6.         return sThreadLocal.get();  
  7.     }  

ThreadLocal类

Implements a thread-local storage, that is, a variable for which each thread has its own value. All threads sharethe sameThreadLocal object, but each sees a different value when accessing it, and changes made by onethread do not affect the other threads. The implementation supportsnull values.


——实现一个线程本地的存储,就是说每个线程都会有自己的内存空间来存放线程自己的值。所有线程都共享一个ThreadLocal对象,但是不同的线程都会对应不同的value,而且单独修改不影响其他线程的value,并且支持null值。


所以说,每个线程都会存放一个独立的Looper实例,通过ThreadLocal.get()方法,就会获得当前线程的Looper的实例。


好了,接下来就要研究一下Handler发送Runnable,究竟怎么发送?

Handler类:

  1. public final boolean post(Runnable r)  
  2.     {  
  3.        return  sendMessageDelayed(getPostMessage(r), 0);  
  4.     }  

  1. private static Message getPostMessage(Runnable r) {  
  2.         Message m = Message.obtain();  
  3.         m.callback = r;  
  4.         return m;  
  5.     }  

可以看出,其实传入的Runnable对象都是封装到Message类中,看下Message是存放什么信息:

Message类:

  1. public final class Message implements Parcelable {    
  2.     public int what;    
  3.     public int arg1;    
  4.     public int arg2;    
  5.     public Object obj;    
  6.     public Messenger replyTo;    
  7.     long when;    
  8.     Bundle data;    
  9.     Handler target;         
  10.     Runnable callback;     
  11.     Message next;    
  12.     private static Object mPoolSync = new Object();    
  13.     private static Message mPool;    
  14.     private static int mPoolSize = 0;    
  15.     private static final int MAX_POOL_SIZE = 10;   

When: 向Handler发送Message生成的时间
Data: 在Bundler 对象上绑定要线程中传递的数据
Next: 当前Message 对一下个Message 的引用
Handler: 处理当前Message 的Handler对象.
mPool: 通过字面理解可能叫他Message池,但是通过分析应该叫有下一个Message引用的Message链更加适合.
其中Message.obtain(),通过源码分析就是获取断掉Message链关系的第一个Message.

       对于源码的解读,可以明确两点:

        1)Message.obtain()是通过从全局Message pool中读取一个Message,回收的时候也是将该Message 放入到pool中。

        2)Message中实现了Parcelable接口


所以接下来看下Handler如何发送Message:

Handler类

  1. /** 
  2.     * Enqueue a message into the message queue after all pending messages 
  3.     * before the absolute time (in milliseconds) <var>uptimeMillis</var>. 
  4.     * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b> 
  5.     * You will receive it in {@link #handleMessage}, in the thread attached 
  6.     * to this handler. 
  7.     *  
  8.     * @param uptimeMillis The absolute time at which the message should be 
  9.     *         delivered, using the 
  10.     *         {@link android.os.SystemClock#uptimeMillis} time-base. 
  11.     *          
  12.     * @return Returns true if the message was successfully placed in to the  
  13.     *         message queue.  Returns false on failure, usually because the 
  14.     *         looper processing the message queue is exiting.  Note that a 
  15.     *         result of true does not mean the message will be processed -- if 
  16.     *         the looper is quit before the delivery time of the message 
  17.     *         occurs then the message will be dropped. 
  18.     */  
  19.    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {  
  20.        MessageQueue queue = mQueue;  
  21.        if (queue == null) {  
  22.            RuntimeException e = new RuntimeException(  
  23.                    this + " sendMessageAtTime() called with no mQueue");  
  24.            Log.w("Looper", e.getMessage(), e);  
  25.            return false;  
  26.        }  
  27.        return enqueueMessage(queue, msg, uptimeMillis);  
  28.    }  

  1. private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {  
  2.        msg.target = this;  
  3.        if (mAsynchronous) {  
  4.            msg.setAsynchronous(true);  
  5.        }  
  6.        return queue.enqueueMessage(msg, uptimeMillis);  
  7.    }  



其实无论是按时间计划发送Message或者Runnable,最终是调用了sendMessageAtTime方法,里面核心执行的是enqueueMessage方法,就是调用了MessageQueue中的enqueueMessage方法,就是把消息Message加入到消息队列中。


这时候问题又来了,如果发送消息只是把消息加入到消息队列中,那谁来把消息分发到Handler中呢?

不妨我们看看Looper类:

  1. /** 
  2.      * Run the message queue in this thread. Be sure to call 
  3.      * {@link #quit()} to end the loop. 
  4.      */  
  5.     public static void loop() {  
  6.         final Looper me = myLooper();  
  7.         if (me == null) {  
  8.             throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
  9.         }  
  10.         final MessageQueue queue = me.mQueue;  
  11.   
  12.         // Make sure the identity of this thread is that of the local process,  
  13.         // and keep track of what that identity token actually is.  
  14.         Binder.clearCallingIdentity();  
  15.         final long ident = Binder.clearCallingIdentity();  
  16.   
  17.         for (;;) {  
  18.             Message msg = queue.next(); // might block  
  19.             if (msg == null) {  
  20.                 // No message indicates that the message queue is quitting.  
  21.                 return;  
  22.             }  
  23.   
  24.             // This must be in a local variable, in case a UI event sets the logger  
  25.             Printer logging = me.mLogging;  
  26.             if (logging != null) {  
  27.                 logging.println(">>>>> Dispatching to " + msg.target + " " +  
  28.                         msg.callback + ": " + msg.what);  
  29.             }  
  30.   
  31.             msg.target.<span style="color:#ff0000;"><strong>dispatchMessage</strong></span>(msg);  
  32.   
  33.             if (logging != null) {  
  34.                 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);  
  35.             }  
  36.   
  37.             // Make sure that during the course of dispatching the  
  38.             // identity of the thread wasn't corrupted.  
  39.             final long newIdent = Binder.clearCallingIdentity();  
  40.             if (ident != newIdent) {  
  41.                 Log.wtf(TAG, "Thread identity changed from 0x"  
  42.                         + Long.toHexString(ident) + " to 0x"  
  43.                         + Long.toHexString(newIdent) + " while dispatching to "  
  44.                         + msg.target.getClass().getName() + " "  
  45.                         + msg.callback + " what=" + msg.what);  
  46.             }  
  47.   
  48.             msg.recycle();  
  49.         }  
  50.     }  
里面loop方法找到调用Handler的dispatchMessage的方法,我们再看看Handler的dispatchMessage:

  1. public void dispatchMessage(Message msg) {  
  2.        if (msg.callback != null) {  
  3.            handleCallback(msg);  
  4.        } else {  
  5.            if (mCallback != null) {  
  6.                if (mCallback.handleMessage(msg)) {  
  7.                    return;  
  8.                }  
  9.            }  
  10.            handleMessage(msg);  
  11.        }  
  12.    }  

dispatchMessage最终是回调了handleMessage。换句话说,Loop的loop()方法就是取得当前线程中的MessageQueue实例,然后不断循环消息分发到对应的Handler实例上。就是只要调用Looper.loop()方法,就可以执行消息分发。

小结:Handler、Message、MessageQueue、Looper的关系原理图:





整个机制实现原理流程:当应用程序运行的时候,会创建一个主线程(UI线程)ActivityThread,这个类里面有个main方法,就是java程序运行的最开始的入口

  1. public static void main(String[] args) {  
  2.         SamplingProfilerIntegration.start();  
  3.   
  4.         // CloseGuard defaults to true and can be quite spammy.  We  
  5.         // disable it here, but selectively enable it later (via  
  6.         // StrictMode) on debug builds, but using DropBox, not logs.  
  7.         CloseGuard.setEnabled(false);  
  8.   
  9.         Process.setArgV0("<pre-initialized>");  
  10.   
  11.         Looper.prepareMainLooper();  
  12.         if (sMainThreadHandler == null) {  
  13.             sMainThreadHandler = new Handler();  
  14.         }  
  15.   
  16.         ActivityThread thread = new ActivityThread();  
  17.         thread.attach(false);  
  18.   
  19.         if (false) {  
  20.             Looper.myLooper().setMessageLogging(new  
  21.                     LogPrinter(Log.DEBUG, "ActivityThread"));  
  22.         }  
  23.   
  24.         <span style="color:#ff0000;">Looper.loop();</span>  
  25.   
  26.         throw new RuntimeException("Main thread loop unexpectedly exited");  
  27.     }  

UI线程就开始就已经调用了loop消息分发,所以当在UI线程实例的Handler对象发送消息或者任务时,会把Message加入到MessageQueue消息队列中,然后分发到Handler的handleMessage方法里。


二、HandlerThread

其实上述就是线程间通讯机制的实现,而HandlerThread和AsyncTask只是对通讯机制进行进一步的封装,要理解也很简单:

HandlerThread类:

  1. public class HandlerThread extends Thread {  
  2.     int mPriority;  
  3.     int mTid = -1;  
  4.     Looper mLooper;  
  5.   
  6.     public HandlerThread(String name) {  
  7.         super(name);  
  8.         mPriority = Process.THREAD_PRIORITY_DEFAULT;  
  9.     }  
  10.       
  11.     /** 
  12.      * Constructs a HandlerThread. 
  13.      * @param name 
  14.      * @param priority The priority to run the thread at. The value supplied must be from  
  15.      * {@link android.os.Process} and not from java.lang.Thread. 
  16.      */  
  17.     public HandlerThread(String name, int priority) {  
  18.         super(name);  
  19.         mPriority = priority;  
  20.     }  
  21.       
  22.     /** 
  23.      * Call back method that can be explicitly overridden if needed to execute some 
  24.      * setup before Looper loops. 
  25.      */  
  26.     protected void onLooperPrepared() {  
  27.     }  
  28.   
  29.     public void run() {  
  30.         mTid = Process.myTid();  
  31.         <span style="color:#ff0000;">Looper.prepare();</span>  
  32.         synchronized (this) {  
  33.             mLooper = Looper.myLooper();  
  34.             notifyAll();  
  35.         }  
  36.         Process.setThreadPriority(mPriority);  
  37.         onLooperPrepared();  
  38.         <span style="color:#ff0000;">Looper.loop();</span>  
  39.         mTid = -1;  
  40.     }  
  41.       
  42.     /** 
  43.      * This method returns the Looper associated with this thread. If this thread not been started 
  44.      * or for any reason is isAlive() returns false, this method will return null. If this thread  
  45.      * has been started, this method will block until the looper has been initialized.   
  46.      * @return The looper. 
  47.      */  
  48.     public Looper getLooper() {  
  49.         if (!isAlive()) {  
  50.             return null;  
  51.         }  
  52.           
  53.         // If the thread has been started, wait until the looper has been created.  
  54.         synchronized (this) {  
  55.             while (isAlive() && mLooper == null) {  
  56.                 try {  
  57.                     wait();  
  58.                 } catch (InterruptedException e) {  
  59.                 }  
  60.             }  
  61.         }  
  62.         return mLooper;  
  63.     }  
  64.       
  65.     /** 
  66.      * Ask the currently running looper to quit.  If the thread has not 
  67.      * been started or has finished (that is if {@link #getLooper} returns 
  68.      * null), then false is returned.  Otherwise the looper is asked to 
  69.      * quit and true is returned. 
  70.      */  
  71.     public boolean quit() {  
  72.         Looper looper = getLooper();  
  73.         if (looper != null) {  
  74.             looper.quit();  
  75.             return true;  
  76.         }  
  77.         return false;  
  78.     }  
  79.       
  80.     /** 
  81.      * Returns the identifier of this thread. See Process.myTid(). 
  82.      */  
  83.     public int getThreadId() {  
  84.         return mTid;  
  85.     }  
  86. }  
可以看得出,HandlerThread继承了Thread,从run()方法可以看出,HandlerThread要嗲用start()方法,才能实例化HandlerThread的Looper对象,和消息分发功能。

所以使用HandlerThread,必须先运行HandlerThread,才能取出对应的Looper对象,然后使用Handler(Looper)构造方法实例Handler,这样Handler的handleMessage方法就是子线程执行了。


三、AsyncTask


AsyncTask现在是android应用开发最常用的工具类,这个类面向调用者是轻量型的,但是对于系统性能来说是重量型的。这个类很强大,使用者很方便就能使用,只需要在对应的方法实现特定的功能即可。就是因为AsyncTask的强大封装,所以说不是轻量型的,先看下源代码吧:

  1. public abstract class AsyncTask<Params, Progress, Result> {  
  2.     private static final String LOG_TAG = "AsyncTask";  
  3.   
  4.     private static final int CORE_POOL_SIZE = 5;  
  5.     private static final int MAXIMUM_POOL_SIZE = 128;  
  6.     private static final int KEEP_ALIVE = 1;  
  7.   
  8.     private static final ThreadFactory sThreadFactory = new ThreadFactory() {  
  9.         private final AtomicInteger mCount = new AtomicInteger(1);  
  10.   
  11.         public Thread newThread(Runnable r) {  
  12.             return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());  
  13.         }  
  14.     };  
  15.   
  16.     private static final BlockingQueue<Runnable> sPoolWorkQueue =  
  17.             new LinkedBlockingQueue<Runnable>(10);  
  18.   
  19.     /** 
  20.      * An {@link Executor} that can be used to execute tasks in parallel. 
  21.      */  
  22.     public static final Executor THREAD_POOL_EXECUTOR  
  23.             = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,  
  24.                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);  
  25.   
  26.     /** 
  27.      * An {@link Executor} that executes tasks one at a time in serial 
  28.      * order.  This serialization is global to a particular process. 
  29.      */  
  30.     public static final Executor SERIAL_EXECUTOR = new SerialExecutor();  
  31.   
  32.     private static final int MESSAGE_POST_RESULT = 0x1;  
  33.     private static final int MESSAGE_POST_PROGRESS = 0x2;  
  34.   
  35.     private static final InternalHandler sHandler = new InternalHandler();  
  36.   
  37.     private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;  
  38.     private final WorkerRunnable<Params, Result> mWorker;  
  39.     private final FutureTask<Result> mFuture;  
  40.   
  41.     private volatile Status mStatus = Status.PENDING;  
  42.       
  43.     private final AtomicBoolean mCancelled = new AtomicBoolean();  
  44.     private final AtomicBoolean mTaskInvoked = new AtomicBoolean();  
  45.   
  46.     private static class SerialExecutor implements Executor {  
  47.         final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();  
  48.         Runnable mActive;  
  49.   
  50.         public synchronized void execute(final Runnable r) {  
  51.             mTasks.offer(new Runnable() {  
  52.                 public void run() {  
  53.                     try {  
  54.                         r.run();  
  55.                     } finally {  
  56.                         scheduleNext();  
  57.                     }  
  58.                 }  
  59.             });  
  60.             if (mActive == null) {  
  61.                 scheduleNext();  
  62.             }  
  63.         }  
  64.   
  65.         protected synchronized void scheduleNext() {  
  66.             if ((mActive = mTasks.poll()) != null) {  
  67.                 THREAD_POOL_EXECUTOR.execute(mActive);  
  68.             }  
  69.         }  
  70.     }  
  71.   
  72.     /** 
  73.      * Indicates the current status of the task. Each status will be set only once 
  74.      * during the lifetime of a task. 
  75.      */  
  76.     public enum Status {  
  77.         /** 
  78.          * Indicates that the task has not been executed yet. 
  79.          */  
  80.         PENDING,  
  81.         /** 
  82.          * Indicates that the task is running. 
  83.          */  
  84.         RUNNING,  
  85.         /** 
  86.          * Indicates that {@link AsyncTask#onPostExecute} has finished. 
  87.          */  
  88.         FINISHED,  
  89.     }  
  90.   
  91.     /** @hide Used to force static handler to be created. */  
  92.     public static void init() {  
  93.         sHandler.getLooper();  
  94.     }  
  95.   
  96.     /** @hide */  
  97.     public static void setDefaultExecutor(Executor exec) {  
  98.         sDefaultExecutor = exec;  
  99.     }  
  100.   
  101.     /** 
  102.      * Creates a new asynchronous task. This constructor must be invoked on the UI thread. 
  103.      */  
  104.     public AsyncTask() {  
  105.         mWorker = new WorkerRunnable<Params, Result>() {  
  106.             public Result call() throws Exception {  
  107.                 mTaskInvoked.set(true);  
  108.   
  109.                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  110.                 //noinspection unchecked  
  111.                 return postResult(doInBackground(mParams));  
  112.             }  
  113.         };  
  114.   
  115.         mFuture = new FutureTask<Result>(mWorker) {  
  116.             @Override  
  117.             protected void done() {  
  118.                 try {  
  119.                     postResultIfNotInvoked(get());  
  120.                 } catch (InterruptedException e) {  
  121.                     android.util.Log.w(LOG_TAG, e);  
  122.                 } catch (ExecutionException e) {  
  123.                     throw new RuntimeException("An error occured while executing doInBackground()",  
  124.                             e.getCause());  
  125.                 } catch (CancellationException e) {  
  126.                     postResultIfNotInvoked(null);  
  127.                 }  
  128.             }  
  129.         };  
  130.     }  
  131.   
  132.     private void postResultIfNotInvoked(Result result) {  
  133.         final boolean wasTaskInvoked = mTaskInvoked.get();  
  134.         if (!wasTaskInvoked) {  
  135.             postResult(result);  
  136.         }  
  137.     }  
  138.   
  139.     private Result postResult(Result result) {  
  140.         @SuppressWarnings("unchecked")  
  141.         Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,  
  142.                 new AsyncTaskResult<Result>(this, result));  
  143.         message.sendToTarget();  
  144.         return result;  
  145.     }  
  146.   
  147.       
  148.     public final Status getStatus() {  
  149.         return mStatus;  
  150.     }  
  151.   
  152.       
  153.     protected abstract Result doInBackground(Params... params);  
  154.   
  155.      
  156.     protected void onPreExecute() {  
  157.     }  
  158.   
  159.       
  160.     @SuppressWarnings({"UnusedDeclaration"})  
  161.     protected void onPostExecute(Result result) {  
  162.     }  
  163.   
  164.       
  165.     @SuppressWarnings({"UnusedDeclaration"})  
  166.     protected void onProgressUpdate(Progress... values) {  
  167.     }  
  168.   
  169.      
  170.     @SuppressWarnings({"UnusedParameters"})  
  171.     protected void onCancelled(Result result) {  
  172.         onCancelled();  
  173.     }      
  174.       
  175.       
  176.     protected void onCancelled() {  
  177.     }  
  178.   
  179.       
  180.     public final boolean isCancelled() {  
  181.         return mCancelled.get();  
  182.     }  
  183.   
  184.       
  185.     public final boolean cancel(boolean mayInterruptIfRunning) {  
  186.         mCancelled.set(true);  
  187.         return mFuture.cancel(mayInterruptIfRunning);  
  188.     }  
  189.   
  190.       
  191.     public final Result get() throws InterruptedException, ExecutionException {  
  192.         return mFuture.get();  
  193.     }  
  194.   
  195.       
  196.     public final Result get(long timeout, TimeUnit unit) throws InterruptedException,  
  197.             ExecutionException, TimeoutException {  
  198.         return mFuture.get(timeout, unit);  
  199.     }  
  200.   
  201.       
  202.     public final AsyncTask<Params, Progress, Result> execute(Params... params) {  
  203.         return executeOnExecutor(sDefaultExecutor, params);  
  204.     }  
  205.   
  206.      
  207.     public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,  
  208.             Params... params) {  
  209.         if (mStatus != Status.PENDING) {  
  210.             switch (mStatus) {  
  211.                 case RUNNING:  
  212.                     throw new IllegalStateException("Cannot execute task:"  
  213.                             + " the task is already running.");  
  214.                 case FINISHED:  
  215.                     throw new IllegalStateException("Cannot execute task:"  
  216.                             + " the task has already been executed "  
  217.                             + "(a task can be executed only once)");  
  218.             }  
  219.         }  
  220.   
  221.         mStatus = Status.RUNNING;  
  222.   
  223.         onPreExecute();  
  224.   
  225.         mWorker.mParams = params;  
  226.         exec.execute(mFuture);  
  227.   
  228.         return this;  
  229.     }  
  230.   
  231.       
  232.     public static void execute(Runnable runnable) {  
  233.         sDefaultExecutor.execute(runnable);  
  234.     }  
  235.   
  236.       
  237.     protected final void publishProgress(Progress... values) {  
  238.         if (!isCancelled()) {  
  239.             sHandler.obtainMessage(MESSAGE_POST_PROGRESS,  
  240.                     new AsyncTaskResult<Progress>(this, values)).sendToTarget();  
  241.         }  
  242.     }  
  243.   
  244.     private void finish(Result result) {  
  245.         if (isCancelled()) {  
  246.             onCancelled(result);  
  247.         } else {  
  248.             onPostExecute(result);  
  249.         }  
  250.         mStatus = Status.FINISHED;  
  251.     }  
  252.   
  253.     private static class InternalHandler extends Handler {  
  254.         @SuppressWarnings({"unchecked""RawUseOfParameterizedType"})  
  255.         @Override  
  256.         public void handleMessage(Message msg) {  
  257.             AsyncTaskResult result = (AsyncTaskResult) msg.obj;  
  258.             switch (msg.what) {  
  259.                 case MESSAGE_POST_RESULT:  
  260.                     // There is only one result  
  261.                     result.mTask.finish(result.mData[0]);  
  262.                     break;  
  263.                 case MESSAGE_POST_PROGRESS:  
  264.                     result.mTask.onProgressUpdate(result.mData);  
  265.                     break;  
  266.             }  
  267.         }  
  268.     }  
  269.   
  270.     private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {  
  271.         Params[] mParams;  
  272.     }  
  273.   
  274.     @SuppressWarnings({"RawUseOfParameterizedType"})  
  275.     private static class AsyncTaskResult<Data> {  
  276.         final AsyncTask mTask;  
  277.         final Data[] mData;  
  278.   
  279.         AsyncTaskResult(AsyncTask task, Data... data) {  
  280.             mTask = task;  
  281.             mData = data;  
  282.         }  
  283.     }  
  284. }  

要理解这个工具类,主要是理解这几个成员对象:

private static final InternalHandler sHandler = new InternalHandler();


    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;


    private final WorkerRunnable<Params, Result> mWorker;


    private final FutureTask<Result> mFuture;


分析:sHandler

消息的发送者和处理者

 sDefualtExecutor

线程执行者。实际上就是一个线程池。

 mWorker

WorkerRunnable实现了Callable接口,就是有返回值的线程任务。

 mFuture

FutureTask是对Callable执行的一个管理类,能够获得线程执行返回的结果,和取消执行等操作。我们再深入一下FutureTask,其中的done()方法是回调方法:

  1. /** 
  2.   * Removes and signals all waiting threads, invokes done(), and 
  3.   * nulls out callable. 
  4.   */  
  5.  private void finishCompletion() {  
  6.      // assert state > COMPLETING;  
  7.      for (WaitNode q; (q = waiters) != null;) {  
  8.          if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {  
  9.              for (;;) {  
  10.                  Thread t = q.thread;  
  11.                  if (t != null) {  
  12.                      q.thread = null;  
  13.                      LockSupport.unpark(t);  
  14.                  }  
  15.                  WaitNode next = q.next;  
  16.                  if (next == null)  
  17.                      break;  
  18.                  q.next = null// unlink to help gc  
  19.                  q = next;  
  20.              }  
  21.              break;  
  22.          }  
  23.      }  
  24.   
  25.     <span style="color:#cc0000;"> done();</span>  
  26.   
  27.      callable = null;        // to reduce footprint  
  28.  }  

只要线程移除或者挂起(取消)的时候,就会调用done()方法,然后在AsyncTask类中的mTask实现了done()方法,最后回调onCancelled()方法。


具体的流程原理是这样的:

1、当第一次AsyncTask在UI线程实例化,其实是实例化Handler,同时UI线程的Looper和MessageQueue绑定在sHandler对象中,之后再去实例话AsyncTask不会在初始化Handler,因为sHandler是类变量。

2、当执行execute方法的时候,实际上是调用线程池的execute方法运行线程

3、callable线程执行体就是调用了doInBackground(mParams)方法,然后以返回结果result当参数,又调用postResult(Result result),实际上就是利用sHandler来发送result到UI线程的MessageQueue中,最后sHandler接受到result后,回调onPostExecute方法。

4、如果主动调用publishProgress(Progress... values)方法,就会利用sHandler把value发送到UI线程的MessageQueue中,然后sHandler接收到value后,回调onProgressUpdate(Progress... values)方法。


注意:sHandler和mDefaultExecutor是类变量

  mWorker和mFuture是实例变量

所以,无论进程中生成多少个AysncTask对象,sHandler和mDefaultExecutor都是同一个,只是任务不同而已。


四、总结

由于我放上去的源代码删除了一些注释,如果还不能了解清楚的话,可以自行去源代码上观看。线程间通讯机制的核心就是Handler+Message+Looper+MessageQueue,只要理解这个四者的实现原理,再多的封装好的工具类也难理解。所以,必须记住一点:android应用开发多线程是必不可少的,所以我们必须遵循UI线程模式开发,就是所有耗时不能在UI线程执行,操作UI必须在UI线程中执行。


原文地址: http://blog.csdn.net/q376420785/article/details/8883008

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值