深入理解Handler消息机制

简介

Handler主要用于是线程之间转换;通过其他线程发送消息,在目标线程消费消息,做到线程之间的切换;
消息机制主要组成部分:
Handler:发送和接受消息(Message);
MessageQueue:消息队列,将Handler发送的消息存在队列中(实际是单链表);
Looper:死循环,不断的从MessageQueue中取出要执行的消息,执行Handler的dispatchMessage()分发消息;

创建Handler对象

主线程

主线程中由于ActivityThread中已经初始化了;
public static void main(String[] args) {
	 Looper.prepareMainLooper();
	 Looper.loop();

}
//方式一:
private Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        return true;

    }
});

//方式二:
MyHandler myHandler = new MyHandler(this);
class MyHandler extends Handler {
    private WeakReference<Activity> weakReference;
    public MyHandler(Activity activity ) {
        weakReference = new WeakReference<Activity>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

    }
}


子线程中

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();
    }
}

发送消息

无论send方法还是post方法最终都是调用enqueueMessage(),将当前消息message插入到MessageQueue中;

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

MessageQueue的enqueueMessage()方法,向MessageQueue中插入数据;MessageQueue中的消息队列其实就是一个单链表,链表中的节点以执行从小到大排序的(最先执行的放在链表头);链表头是成员变量mMessages;

 boolean enqueueMessage(Message msg, long when) {
    synchronized (this) {
		//当前Looper已经退出,则不再往队列中插入消息;
        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;
        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 {
            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;
}

消费消息

Looper类的loop()死循环,不断的从MessageQueue中获取消息消费;

 public static void loop() {
	//1:得到当前线程的Looper对象
    final Looper me = myLooper();
	//必须要先调用Looper.prepare()
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;

    // Make sure the identity of this thread is that of the local process,
    // and keep track of what that identity token actually is.
    Binder.clearCallingIdentity();
    final long ident = Binder.clearCallingIdentity();

    for (;;) {
		//2:从MessageQueue中获取消息;当MessageQueue中存在对应的消息时,返回对应的Message,否则阻塞,一直等待;
        Message msg = queue.next(); // might block
		//消息为null,结束循环;
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
			//3:消费消息,Handler类的dispatchMessage();
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
        }
    }
}

1:myLooper()方法,每个线程都对应一个ThreadLocal类,线程私有对象,可以实现线程安全,以空间换时间;

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

2:主要看MessageQueue的next()方法,死循环,从MessageQueue中获取消息;只有找到了对应开始执行时间的消息或者主动退出了Looper.loop()方法才会结束死循环;

Message next() {
    final long ptr = mPtr;
	//如果当前Looper已经退出,ptr=0;直接返回null,Looper.loop()退出循环;
    if (ptr == 0) {
        return null;
    }

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        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;
			//一般情况下msg.target不为null,从MessageQueue类的enqueueMessage()可以知道;
            if (msg != null && msg.target == null) {
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
			//当前队列不为空
            if (msg != null) {
				//当前时间小于队列头消息的执行时间,得到消息执行的等待时间;
                if (now < msg.when) {
                    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;
                    msg.markInUse();
                    return msg;
                }
            } else {//否则队列为null;
                // No more messages.
                nextPollTimeoutMillis = -1;
            }
			//正在中断Looper.loop()方法
            if (mQuitting) {
                dispose();
                return null;
            }
        }
    }
}

Looper类的loop()和MessageQueue的next()方法是最核心的地方;

3:Handler类的dispatchMessage()

public void dispatchMessage(Message msg) {
	//post()发送消息的回调
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
		//直接创建Handle的对象,并且返回true;
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
		//具体实现类的回调
        handleMessage(msg);
    }
}
  • 注意

在退出线程前,调用quit(),quitSafely();

问题

  • Handler和Looper以及MessageQueue的数量上对应关系?
    在创建Handler对象模块在子线程创建Handler或者ActivityThread的Main()方法依次
Looper.prepare();
Looper.loop();

Looper的prepare()方法中创建Looper对象,并且保存在ThreadLocal(线程私有空间中),并且一个线程只能初始化一个Looper对象,所以 Looper和MessageQueue是一一对应的关系,并且属于线程范畴类的变量即线程私有变量;一个线程中可以有任意个Handler

private static void prepare(boolean quitAllowed) {
  if (sThreadLocal.get() != null) {
       throw new RuntimeException("Only one Looper may be created per thread");
   }
   sThreadLocal.set(new Looper(quitAllowed));
}
//创建MessageQueue;
private Looper(boolean quitAllowed) {
   mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}
  • 一个线程中可以有N个Hander,那消息如何发送到对应的Handler处理呢?
    主要看Looper的loop()方法在找到要处理的对应的Message之后,调用
 msg.target.dispatchMessage(msg);

进入Message类看到,保存有那个那个发送的对象Hander;

  • Handler是如何切换线程的?
    在了解Hander和Looper以及MessageQueue数量的对应关系之后,就很好理解了;
    首先在主线程创建Looper,MessageQueue之后,创建Handler,在子线程通过Handler对象将Message发送到主线程的MessageQueue中;
    然后通过Looper的loop()方法取出Message,调用Hander的回调,即实现了线程切换;

以上就是Handler消息机制的主要内容,如有问题,请多指教,谢谢!

你可能感兴趣的:(Framework)