android中把java中TheadLocal类中内部类ThreadLocalMap换成了Values,并且方法也换了;
android中线程存储的就是ThreadLocal.Values了;
线程中用Handler的方式:
new Thread(){
public void run(){
Looper.prepare();
Handler handler = new Handler();
}
};
Looper.loop();会阻塞线程,一直等待消息唤醒线程,继续执行;
来看看Handler:
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(boolean async) {
this(null, async);
}
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;
}
以上就是Handler的构造函数;
无参数的构造函数实际上调用的是最后一个构造函数,那么看看最后一个构造函数:
1.检查当前Handler是否是静态的,否则有内存泄露风险;
2.获得当前线程的Loop对象;
3.获得消息队列对象;
4.Callback对象;
第二步如果没有获得Looper对象就会抛出
Can't create handler inside thread that has not called Looper.prepare()
因此内部线程需要Looper.prepare(),Looper.loop();
主线程即(ActivityThread)已经做好了Looper.prepare(),Looper.loop();因此主线程不需要,可以直接new Hander();
其他线程在创建Handler对象之前需要run方法中Looper.prepare();最后Looper.loop();
看看Looper类的prepare()方法:
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));
}
从第二个函数可以知道 prepare()只能调用一次,每一个线程的Looper对象只能有一个;
以上代码也说明了prepare()方法是把looper对象绑定到当前线程上(通过ThreadLocal实现Looper对象绑定到线程);
看看Looper类的loop()方法:
prepare是绑定,那么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();
}
}
在无限循环中:
Message msg = queue.next();
queue.next()是个阻塞方法,没有从消息队列中拿到消息线程就block状态;
获得消息后执行
msg.target.dispatchMessage(msg);
msg.target也就是Message绑定的Handler对象;执行Handler中的dispatchMessage方法;
以上就是整个handler+looper+messagequeue+thread的流程;
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
看看Handler的dispatchMessage源码:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
优先执行msg中的callback,handler.post(new Runnable(){}); callback就是new Runnable(){}对象;
再次执行mCallback中的handleMessage, mCallback是构造函数中传递的对象;
优先级最低的是handler自身的handleMessage对象;
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
回到Handler对象,handler对象实际上是与Looper对象绑定,绑定到哪个线程的looper对象上就能让哪个线程执行handler的处理代码逻辑;
因此不必在当前线程下创建Handler对象; HandlerThread体现了这种用法;
<pre name="code" class="java"> MyHandlerThread handlerThread = new MyHandlerThread("myHanler");
handlerThread.start();
handler = new Handler(handlerThread.getLooper(), handlerThread);
private class MyHandlerThread extends HandlerThread implements Callback {
public MyHandlerThread(String name) {
super(name);
}
@Override
public boolean handleMessage(Message msg) {
//打印线程的名称
System.out.println(" handleMessage CurrentThread = " + Thread.currentThread().getName());
return true;
}
}
或者:
MyHandlerThread handlerThread = new MyHandlerThread("myHanler");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
}
});