彻底理解handler的实现原理

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

涉及到的内容:

  • Loop
  • Message
  • MessageQueue
  • ThreadLocal
  • Handler

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


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;
创建Handler对象时,在构造方法中会获取Looper和MessageQueue的对象

  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 这个类 就是每次创建一次都会有一个单独的线程出现,每个线程自己做自己的事情 互不干扰。其实呢这个Looper就是为了在该线程中 创建一个messageQueue。然后后面是把handler放到message中。然后再把message放到了messageQueue中。这样 这个handler就可以发送和接受 在该线程中的所有操作了。如果还不理解ThreadLocal的意思。我推荐google一下。张孝祥ThreadLocal。绝对让你理解他的含义。
比如你有一个主线程和10个子线程,现在呢这11个线程里面都new Handler()。就会有11个不同的ThreadLocal。他们之前不顾干扰。然后呢你就需要在这10个子线程里面写都写一遍Looper.prepare()和Looper.loop()。

我们现在已经有了获取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();
    }

Looper和MessageQueue是通过Looper.prepare的时候创建的,在一个线程里面prepare()只能执行一次

从这里我们可以看出来 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

Linux的一个进程间通信机制:管道(pipe)。原理:在内存中有一个特殊的文件,这个文件有两个句柄(引用),一个是读取句柄,一个是写入句柄

主线程Looper从消息队列读取消息,当读完所有消息时,进入睡眠,主线程阻塞。子线程往消息队列发送消息,并且往管道文件写数据,主线程即被唤醒,从管道文件读取数据,主线程被唤醒只是为了读取消息,当消息读取完毕,再次睡眠

这里就是到了我们上面说的两行代码 没有执行的原因是因为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) {// 第一优先Runnable对象
            handleCallback(msg);
        } else {
            if (mCallback != null) {// 第二优先Callback对象
                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) {
          。。。
           //对消息的重新排序,通过判断消息队列里是否有消息以及消息的时间对比
            msg.when = when;
            Message p = mMessages;//获取msg
            boolean needWake;
            if (p == null || when == 0 || when < p.when) { 
             // 如果消息队列中没有消息,或者当前消息的时候比队列中的消息的时间小,则让当前消息成为队列中的第一条消息
                // 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();
                 // 当前消息要插入到这个prev消息的后面
                Message prev;
                  // 这个死循环用于找出当前消息(msg)应该插入到消息列表中的哪个消息的后面(应该插入到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

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值