主线程threadlocal什么时候执行set方法?
来源:9-2 说说threadLocal的原理
2021冲冲冲
2020-04-14
老师,你说的每个线程去获取looper时候,获取到的looper实例都不同,问一下是怎么做到的,主线程什么时候put了那么多对应线程的looper进去?
写回答
2回答
-
慕仰8246418
2022-11-16
threadlocal的set方法把looper对象存在中,threadlocal只是作为key
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } Thread.java/* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null;
00 -
风语
2020-04-19
threadLocal相当于每个线程自己的局部变量,我们看looper的源码会发现looper其实是存在thread local里的。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
主线程不会去put looper到别的线程,只有子线程自己调用Looper.prepare才会创建一个looper
00
相似问题