码迷,mamicode.com
首页 > 其他好文 > 详细

彻底理解handler的实现原理

时间:2016-05-09 20:44:02      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:

说到handler大家都很熟悉,自己也用了很久,再此总结一下 从handler的源码角度看看handler是如何执行的。

涉及到的内容:

  • Loop
  • Message
  • MessageQueue
  • ThreadLocal
  • Hadnler

这些东西还是挺多的。那么我们先看一个栗子吧


public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_http).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text();
            }
        });

    }

    private void text() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Handler handler1 = new Handler() {//为了说明问题的写法
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Log.e(TAG, "handle1: " + msg.what + "-thread1-" + Thread.currentThread().getName());
                    }
                };
                Message msg = new Message();
                msg.what = 2;
                handler1.sendMessage(msg);
                handler2.obtainMessage(1).sendToTarget();
                handler2.obtainMessage(4).sendToTarget();
                Looper.loop();
                Log.e(TAG, "loop 执行完毕");
                handler2.obtainMessage(3).sendToTarget();
            }
        }).start();
    }

    Handler handler2 = new Handler() {//普通写法
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e(TAG, "handle2: " + msg.what + "-thread2-" + Thread.currentThread().getName());
        }
    };
}

两种写法: 普通写法 和 为了说明问题的写法。 先不管为什么这么写。先执行下代码。你们觉得会怎么执行呢。
结果是这样的

E/MainActivity: handle1: 2-thread1-Thread-18270   :handler1 先发送消息,并且获取到消息。都发生在子线程
E/MainActivity: handle2: 1-thread2-main         : handler2 发送消息 获取消息
E/MainActivity: handle2: 4-thread2-main         : handler2 发送消息 获取消息

但我们的两行代码没有执行

                这两行代码没有执行
                Log.e(TAG, "loop 执行完毕");
                handler2.obtainMessage(3).sendToTarget();

一些问题:

  • 为什么在子线程里面 执行了 Looper.prepare();和 Looper.loop(); 两行代码 但是在主线程的里面没有写?
  • Looper.prepare();和 Looper.loop();是什么意思 他们的放置位置有什么限制么?
  • 为什么那两行代码没有执行?
  • handler1.sendMessage(msg);和 handler2.obtainMessage(1).sendToTarget();区别是什么?
  • 为什么 handlerMessage()可以获取到消息他们的底层是如何实现的呢?

Looper的相关问题

先看一下new Handler();的源码 带我们了解looper;
  public Handler() {
        this(null, false);
    }

  public Handler(Callback callback, boolean async) {
      ...省略部分代码..
        mLooper = Looper.myLooper();//这里获取一个mLooper
        if (mLooper == null) {//如果mLooper为null抛出异常
            throw new RuntimeException(
                "Can‘t create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

看到这里知道了。在使用new Handler()之前必须要有一个mLooper这个对象。不然的话会抛出异常。
接着看

  public static @Nullable Looper myLooper() {//这里就返回一个mLooper 了
        return sThreadLocal.get();
    }

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

这里有个注意的就是ThreadLocal 这个类 是static和 final的类型 就是 没创建一次都会有一个单独的而且唯一的ThreadLocal
比如主线程的ThreadLocal 就只有一个。 你开启一百个new Handler()。就会有100个不同的ThreadLocal。他们之前不顾干扰。

我们现在已经有了获取looper的方法了。肯定也得有set的方法。
看 Looper.prepare();方法

   public static void prepare() {
        prepare(true);
     }

    private static void prepare(boolean quitAllowed) {//这个参数的意思就是这个messagequeue是否可以销毁
        if (sThreadLocal.get() != null) {//这里执行了获取ThreadLocal方法。如果已经存在了抛异常。所以 prepare方法在一个线程里只能执行一遍。
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed)); //这里执行了我们想要的set方法。 
    }

//这个looper方法里面直接new出来了 MessageQueue() 和获取当前线程作为 标示
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }


  // True if the message queue can be quit.
    private final boolean mQuitAllowed;//这里是判断该messageQueue是否可销毁
     MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;//赋值
        mPtr = nativeInit();
    }

从这里我们可以看出来 new Handler();10次。会有10个Threadlocal,会有10个MessageQueue。
到这里我们还有个疑问就是为什么主线程没有写Looper.prepare();

我们新来看ActivityThread这个类。这个类创建主线程。


    public static void main(String[] args) {
        。。。。
        Looper.prepareMainLooper();//有点儿类似prepare的方法

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();//这里也出现了loop的方法了。

        throw new RuntimeException("Main thread loop unexpectedly exited");//loop()方法后面只有一句异常。好像loop不会被停止一样。
    }

    public static void prepareMainLooper() {
        prepare(false);//这里穿的值是false。说明该线程中的messageQueue是不可以被销毁的。
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();//prepare里面执行set方法。这里执行get方法获取Looper
        }
    }

到这里就明白了为什么 子线程执行 Looper.prepare()方法了。
再来看Looper.loop();

 public static void loop() {
        final Looper me = myLooper();//获取looper
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn‘t called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//获取该looper下的queue

                。。。。。。
        for (;;) {//死循环。我看的源码是api 23的。记得以前是while(true)。为什么捏
            Message msg = queue.next(); // might block  
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            。。。。。
            msg.target.dispatchMessage(msg);//这个方法很重要

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn‘t corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

这个Looper.loop()方法就是一个死循环不断地从messageQueue中获取msg

这里就是到了我们上面说的两行代码 没有执行的原因是因为loop()是死循环。后面的代码不会执行了
我们发现了这里有一个

 /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

到这里呢。我们就理解了。

 Handler handler1 = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);

                    }
                };

这里其实每次就是重写了一个handlermessage()的方法。来更新我们的线程。

sendMessage()和obtainmessage()

handler发消息有两类方法:sendMessage()和obtainmessage() 其他的什么延迟啊。

sendMessage()方法

所有sendMessage()类的方法都会执行到这里

    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }

     private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);//忘messageQueue里面插入msg。
    }

这个Message呢是类似于链表的写法。(觉得算法终于有用了)
什么事链表捏
技术分享

就是这样。msg不断地只想下一个msg。

  boolean enqueueMessage(Message msg, long when) {
     。。
        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;//获取时间
            Message p = mMessages;//获取msg
            boolean needWake;
            if (p == null || when == 0 || when < p.when) { //不断地把msg添加到msg链表的最后面
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else { //意思是 后来传入的消息 要执行在 之前消息之前。。就是在链表的都一处插入一条消息
                // Inserted within the middle of the queue.  Usually we don‘t have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) { 
                nativeWake(mPtr);
            }
        }
        return true;
    }

再看一下obtainmessage();

 public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();//消息池里面没有消息就new 一个新的消息  所有的消息链表在messageQueue中
    }

这个呢就是链表的形式,把消息池里的第一条数据取出来,然后把第二条数据变为第一条。这样循环的取数据
技术分享
一个循环之后呢
技术分享

然后都会执行sendToTarget();把消息发出去

 public void sendToTarget() {
        target.sendMessage(this);这样就是sendMessage()一样啦。 
    }

可以看到obtainmessage()这样呢就减少了message的创建。

总结

new Handler的时候Handler就已经拿到了线程的Looper 。MessagQueue

handler发送消息:
把Handler保存到Message里。
把Message保存到messageQueue里。

ActivityThread.java主线程入口类
在main()方法中存入了Looper.prepareMainLooper();(这里已经创建了Looper,messagequeue)
然后不断地执行获取消息的方法:Looper.loop();去出message,然后调用handler的dispatchMessage(msg);

一张图解决所有问题
技术分享

尊重原创http://blog.csdn.net/wanghao200906/article/details/51355018

彻底理解handler的实现原理

标签:

原文地址:http://blog.csdn.net/wanghao200906/article/details/51355018

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!