ThreadLocal是如何实现线程隔离的?
ThreadLocal(一)设计ThreadLocal的目的
ThreadLoca(二)Looper中ThreadLocal的使用
ThreadLocal在android中的应用,就是在Looper类中。
Looper的使用,可以参考这篇:Android 两个子线程来回通信!,核心代码是:
void run(){
Looper.prepare(); //初始化Lopper
handler.sendMsg();
Looper.loop(); //循环遍历消息队列
}
看看prepare()方法:
prepare方法,初始化了一个Looper对象,放在ThreadLocal中。如果ThreadLocal中,已经有了,就会抛出运行期异常。这样,就实现了一个线程中,只有一个looper对象。
那在哪里取出这个Looper对象了?在myLooper方法中:
不出意料的化,在Looper.loop()方法中,要用到myLooper(),看看looper()方法:
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;
...
...
boolean slowDeliveryDetected = false;
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
final Printer logging = me.mLogging;
...
}
}
Looper对象为什么要存在ThreadLocal中?
ThreadLocal在实际项目中的应用
线程封闭与ThreadLocal
正确理解Thread Local的原理与适用场景