Handler 知识总结

官方介绍

A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it – from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

本人翻译

Handler用来处理或发送已关联线程的消息队列中的消息和Runnable对象。每个Handler实例关联到单个线程和线程的消息队列。当创建一个新Handler时,Handler将被绑定到创建它的线程和消息队列;从此时开始,Handler将传递消息和Runnable到消息队列并处理消息队列弹出的消息和Runnable.
Handler有一下2中用法:

  1. 给待执行的消息&Runnable进行排队,即将他们放到消息队列中。
  2. 将要执行的动作排队到其他线程。 handler关联到A线程,B线程有handler的引用,此是handler可以将消息发送到A线程中。
Looper

在handler这块,我们不能回避Looper(貌似只在Android中有)。Looper是给线程运行消息循环的类。进程没有默认的消息循环。通过在线程中调用prepare方法来创建,调用loop来循环。调用Looper.quit()退出循环。
通过Handler来进行消息循环交互。
创建looper方法

class LooperThread extends Thread {
        public Handler mHandler;
  
        public void run() {
            Looper.prepare();
  
            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    // process incoming messages here
                }
            };
  
            Looper.loop();
        }
    }

loop循环方法(注:截取部分代码):

    public static void loop() {
        final Looper me = myLooper();
        final MessageQueue queue = me.mQueue;
        for (;;) {
            Message msg = queue.next(); // might block
            try {//分发消息,调用Handler的dispatchMessage方法
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            msg.recycleUnchecked();
       }

上面代码中 for (; ; )这个写法会导致死循环????

MessageQueue

消息队列是一个低层次的类,保管looper分发的消息列表。消息不会直接添加到消息队列,而是通过Looper 关联的Handler。消息队列的next()方法会阻塞调用它线程。

    Message next() {
        for (;;) {
         nativePollOnce(ptr, nextPollTimeoutMillis);
            synchronized (this) {
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值