前言
- ThreadLocal在哪出现的?
- ThreadLocal到底是个啥东西?
- ThreadLoca在Android线程消息模型中作用是啥?
- 等等。。。
学习目标
- 了解ThreadLoca类是个啥东西以及他在线程消息模型中扮演的角色,它的作用。
代码介绍
- 最近在研究Android线程消息模型时,在Lopper.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));
}
可以看到这个有个判断:
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
看这个抛出的异常字面意思是说“在一个线程中只允许存在一个looper对象”。即就是判断线程中是否已经存在looper。
我们都知道Looper.prepare()是可以让一个work thread 升级为带有消息队列MQ的消息线程的,升级的具体这里暂不多说。
怀着好奇心,我又继续查看ThreadLocal.get()方法,于是又看到了这么一段代码:
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);
}