handler的内部机制和handler.post

 handler.sendMessage(msg);之后handler是怎么处理及得到Message的呢
 
 先整体后局部
 
 整体的流程:
 
handler的内部机制和handler.post 

 从上图看到,handler.sendMessage(msg)会把msg通过
 
MessageQueue queue = mQueue;
 queue.enqueueMessage(msg, uptimeMillis);
 
 方法塞入MessageQueue中,而这个MessageQueue是通过mQueue来的,mQueue是什么呢
 
mLooper = Looper.myLooper();
 mQueue = mLooper.mQueue;
 
 其中的Looper.myLooper():
 
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
 
 public static Looper myLooper() {
        return sThreadLocal.get();
    }

  
 而ThreadLocal是什么,从它的get方法中看到

/**
     * Returns the value of this variable for the current thread. If an entry
     * doesn't yet exist for this variable on this thread, this method will
     * create an entry, populating the value with the result of
     * {@link #initialValue()}.
     *
     * @return the current value of the variable for the calling thread.
     */
    @SuppressWarnings("unchecked")
    public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }
  它就是返回 当前线程的线程局部变量副本,所以ThreadLocal的中文名叫线程局部变量,不是什么本地线程哦。



   Android有个方法是handler.post(Runnable),他是用来将runnable加入当前线程队列中等待执行的,注意上面两个关键字:线程队列、等待执行,比如你想让加载完某张图片前显示一个加载框,加载完后显示在界面上,你就可以这样用:

new Thread()
	{
  public void run()
	{
		loadPic();//这里去加载图片
		handler.post(new Runnable()
		{
			@Override
			public void run()
			{
                            //loadPic();写这里就错了!!!
                            instanceView();
			}
		});
	};
}.start();



我的博客其他文章列表 
http://my.oschina.net/helu



你可能感兴趣的:(handler的内部机制和handler.post)