如果想看懂Android中Handler源码,那么ThreadLocal类的作用必须要懂,ThreadLocal的出现解决了线程存存储自己的数据不发生异常,而不是解决线程安全问题,看下例子:
package thread;
public class ThreadLocalTest {
static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
new Thread(){
@Override
public void run() {
threadLocal.set("第一个线程");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-----"+threadLocal.get());
}
}.start();
new Thread(){
@Override
public void run() {
threadLocal.set("第二个线程");
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-----"+threadLocal.get());
}
}.start();
threadLocal.set("main线程");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-----"+threadLocal.get());
}
}
ThreadLocal使用很简单,就是一个set() get()方法 一个设置值 一个获取值,如果不调用set()方法设置值的话 get()的值为null,
除非你重写它的方法
protected T initialValue() {
return null;
}
我们可以理解它内部是一个map去维护,key是Thread,value是你通过set()方法的值,在Handler源码中value是Looper.
手机扫一扫
移动阅读更方便
你可能感兴趣的文章