ThreadLocal
ThreadLocal是一个线程内部的数据存储类。它可以为各线程存储数据,同时只能由当前线程获取到存储的数据,对于其他线程来说则获取不到。它可以在不同线程中维护一套数据的副本,并且彼此互不干扰。
一言不合上代码:
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
public static void main(String[] args) {
threadLocal.set(1);
System.out.println(Thread.currentThread().getName() + "--value:"
+ threadLocal.get());
new Thread("Thread#1") {
public void run() {
threadLocal.set(2);
System.out.println(Thread.currentThread().getName() + "--value:"
+ threadLocal.get());
};
}.start();
new Thread("Thread#2") {
public void run() {
System.out.println(Thread.currentThread().getName() + "--value:"
+ threadLocal.get());
};
}.start();
}复制代码
输出结果为:
main--value:1
Thread#1--value:2
Thread#2--value:null复制代码
ThreadLocal内部为当前线程维护了一个ThreadLocalMap。key是ThreadLocal对象,value则是需要设置的值,存储在Entry中。
注意
Handler创建时,会获取到消息队列和当前线程的Looper对象来构建消息循环系统,那么如何获取到当前线程的Looper呢?就是用到ThreadLocal,它存储了Looper对象。保证了不同线程间提供对应的Looper对象。
因此保证了一个线程只有一个Looper对象
注意:线程是默认没有Looper的,如果需要使用Handler,就必须为线程创建Looper。
只所以可以在Activity中直接实例化Handler,是因为ActivityThread作为程序的入口,已经实例化好了Looper对象。
public final class ActivityThread {
// 省略...
public static void main(String[] args) {
// 省略...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
}复制代码
因此如果需要在子线程中使用Handler,则必须先实例化Looper。
new Thread("Thread#1"){
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler();
handler.sendEmptyMessage(0);
Looper.loop();
}
}.start();复制代码