预备知识:
线程局部存储(TLS)
我们可以从变量作用域的角度来理解什么是线程局部存储:
函数内部变量 :作用域为该函数,即每次调用该函数时该变量都会回到初始值。
类内部变量:其作用域为该类产生的对象,即只要对象没有被销毁,则对象的变量一直保持。
类内部静态变量:其作用域是整个进程,即只要在该进程中,即该变量的值就一直保持,无论该类构造过多少对象,该变量只有一个赋值,并一直保持。(编译器内部会为静态变量分配单独的内存空间)
线程局部存储:其作用域为同一个线程,当同一个线程中调用线程局部存储对象时,其值只有一个。
ThreadLocal
java是用 ThreadLocal 类来存储线程局部存储对象的类,它的构造函数为空,是利用set()和get()方法来保存和获取线程局部存储对象的。该对象将所有同一个线程的线程局部存储对象保存在 values对象内(没有具体了解应该是链表结构)。
public void set(T value) { Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values == null) { values = initializeValues(currentThread); } values.put(this, value); }
set方法内首先根据线程对象获取values对象,若没有则初始化,将要保存的对象put进去。
public T get() { // Optimized for the fast path. Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values != null) { Object[] table = values.table; int index = hash & values.mask; if (this.reference == table[index]) { return (T) table[index + 1]; } } else { values = initializeValues(currentThread); } return (T) values.getAfterMiss(this); }
get方法,首先是利用当前线程来获取存储“线程局部存储”对象的values对象,然后获取存储的所有对象的数组table,然后根据hash和value.mask得到获取的index值,最终获取相应的线程局部存储对象。
好了预备知识介绍完了,下面进入正题:
为什么要介绍线程局部存储呢?其实我们activity创建前activity所在的线程就会调用Looper.prepare()方法和Looper.loop()方法:为该线程创建存储“线程局部存储”对象的对象sThreadLocal,并为activity所在的线程创建一个Looper对象,并将Looper保存为线程局部存储对象的values里面,并启动消息队列运行机制。
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
当不调用preprare()时sTreadLocal为空
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)); }
该方法首先判断是否已经存储了Looper若存储了就抛出异常,因为每个线程只能有一个Looper对象,若没有保存就会保存Looper为线程局部存储对象。
而上面的new Looper()创建Looper的方法原型如下:
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
Looper会创建一个消息队列。
下面我们看看创建了activity前调用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(); } }
myLooper()是获取当前线程的Looper对象
msg.target.dispatchMessage(msg),msg.target是获取发送msg消息对象,即handler;handler调用dispatchMessage来处理消息。handler 里面的dispatchMessage()里面实际是利用handleMessage()处理的,因此,当我们想要异步处理消息的时候只需要构建自己handler,并覆写它们的消息处理的方法。因为Looper中msg会自动获取我们创建的handler,并调用我们自己覆写的处理方法。
msg.recycleUnchecked() Message对象里面用数据池保存message对象,因此为了频繁删除创建,当消息处理完后就标记为空闲状态回收重复利用。
queue.next() 是从消息队列MessageQueue中取出一条消息:
Message next() { // Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. final long ptr = mPtr; if (ptr == 0) { return null; } int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } 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; } // Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); return null; } // If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } // Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } }
nativePollOnce(ptr , nextPollTimeoutMillis)是一个JNI函数,其作用是从消息队列中取出一个消息。MessageQueue内部本身没有保存消息队列,真正的消息队列保存在C代码中。C环境中创建了一个NativeMessageQueue数据对象,也就是nativePollOnce方法的第一个参数ptr,它是个long变量,在构造MessageQueue时候初始化,在C环境中利用它来获得NativeMessageQueue对象.在C环境中,若消息队列中无消息,会导致当前线程挂起(wait),若队列有消息,则C代码会把当前消息复值给java环境中的mMessages变量。
synchronized (this) 同步代码块,
主要是判断执行消息的时间是否到了(有的消息本身指定了处理的时刻,消息是以队列形式存储,若读取没到执行时刻就执行下一个消息,下次读取仍然从队列头读取,每次都会判断是否到了执行时间),若到了就返回消息,并将mMessages置为空;若时间没有到则尝试读取下一个消息。
若mMessage为空,则队列里没有消息,调用mPendingIdleHandlers里的空闲回调函数。
MessageQueue是用enqueueMessage函数添加消息的:
boolean enqueueMessage(Message msg, long when) { if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } 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; 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(); 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; }
该方法先将参数msg赋值给mMessage,然后利用nativeWake写入消息到C环境,若消息线程处于wait状态,则唤醒。