您的位置:首页 > 移动开发 > Android开发

Handler实现线程间通信的原理

2016-08-23 13:50 381 查看
本文以Handler对象的创建和消息发送为切入点,讲述背后的实现原理。

一. Handler对象创建的背后过程

public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}

mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}


public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}


返回当前线程的Looper实例化对象
/**
* Return the Looper object associated with the current thread.  Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}


从Handler构造方法来看,每个Handler对象,都拥有成员变量looper对象mLooper,消息队列对象mQueue,而这种消息队列对象也是mLooper成员变量,这个Looper对象要么是使用者直接传进来的,要么是通过Looper.myLooper()得到的。

下面再来看看Looper的创建,Looper对象对外提供静态方法prepare() 创建,但构造方法是私有的,不能直接实例化。

每个线程至多有一个Looper对象,否则会抛运行时异常。创建Looper对象时,会创建一个MessageQueue对象作为其成员变量。

public static void prepare() {
prepare(true);
}
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}


MessageQueue是由Message对象组织成链表结构的消息队列,Message对象是序列化对象,除了通信的数据外,一个很关键的是成员变量就是target用来存储通信Handler对象。

由上面的代码片段可知,要实现Handler线程间通信,必须要首先通过Looper的prepare()实例化对象,但是有些同学可能平时使用Handler时都没有操作过Looper,那Looper初始化在哪里进行的呢。

其实在app启动的时候,ActivityThread main方法里都已经通过prepareMainLooper()创建了,它是主线程的Looper实例,相比子线程的初始化稍有不同。具体参看如下代码:

public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();

// CloseGuard defaults to true and can be quite spammy.  We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);

Environment.initForCurrentUser();

// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());

// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);

Process.setArgV0("<pre-initialized>");

Looper.prepareMainLooper();

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

throw new RuntimeException("Main thread loop unexpectedly exited");
}


二. Handler对象触发线程通信的背后过程

当子线程通过Handler的sendMessage触发消息时,是怎么和主线程通信的呢,这个时候Looper就真正起作用了,看Looper的loop()方法:

/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
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 (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}

// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

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


通过上面的代码可知:这个是死循环代码,一直从MessageQueue里取msg,通过拿到msg的target对象,上面有特意强调过这个就是我们的Handler对象,调用它的dispatchMessage方法,具体实现看源代码:

/**
* 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);
}
}


看到handleMessage方法估计大家都熟悉了,这就是我们经常重写Handler类的handleMessage方法,那么loop()方法又在哪里调用的呢,其实细心的同学在上面的ActivityThread main方法里都已经发现了,在Looper初始化成功后,就会调用loop()方法一直检查是否有消息,有消息就调用这个handler对象的dispatchMessage方法,至此子线程和主线程通信过程结束了。

聪明的同学可能会有疑问,Android中为什么主线程不会因为Looper.loop()里的死循环卡死?

其实主线程确实会一直卡在loop()循环里,只是因为主线程又开辟了其它Binder子线程来处理,你没有感觉到而已,具体分析参看知乎牛人的回答:http://www.zhihu.com/question/34652589

总结:Thread ,Looper,MessageQueue,Message,Handler的之间关系

一个Thread至多有一个Looper,需要通过Looper.prepare()初始化和Looper.loop()处理分发给对应的Handler对象处理

一个Looper有且有一个MessageQueue,通过Looper.loop()取出MessageQueue的Message进行处理,但是可以服务于多个Handler对象。

MessageQueue是由Message对象组织成链表结构的消息队列,而每个Message对象都唯一对应一个Handler对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息