JDK1.5以后提供了许多方便的关于线程的类,比如ThreadLocal,一个可以在线程范围内共享数据的类:
使用:
public class ThreadLocalDemo2 {
public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
//从threadlocal取出当前线程所存储的变量,这里没有存过所以应为null
System.out.println(threadLocal.get());
//给当前线程存储相关联的值
threadLocal.set(2);
//再取一次,这次就有了。
System.out.println(threadLocal.get());
}
}
threadlocal的使用非常简单,就set,get它自动与当前所调用set,get方法的线程绑定,不用我们去判断,相当于一个Map<Thread,Object> map,然后map.put(Thread.currentThread,object),这样就把值与相关的线程关联起来了呗(只是举例而已,内部实现没这么简单)。
使用Threadlocal,模拟Android源码中的Handler消息机制中Looper的实现:
/**
* Looper类
* @author lenovo
*
*/
class Looper {
private static final ThreadLocal<Looper> THREAD_LOCAL = new ThreadLocal<>();
public static void prepared(){
Looper looper = THREAD_LOCAL.get();
if(looper == null){
THREAD_LOCAL.set(new Looper());
}
}
public static Looper getLooper(){
return THREAD_LOCAL.get();
}
}
这就是我们Android总常见的Looper,他就是通过ThreadLocal来完成与线程的绑定的,一个线程对应一个Looper,一个Looper中携带一个MessageQuene。
调用测试:
public class ThreadLocalDemo2 {
public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
//主线程取Looper
System.out.println("main Thread..."+Looper.getLooper());
//子线程取Looper
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +"..."+Looper.getLooper());
//给子线程设置Looper
Looper.prepared();
//子线程取Looper
System.out.println(Thread.currentThread().getName() +"取..."+Looper.getLooper());
}
}).start();
//给主线程设置Looper
Looper.prepared();
//主线程取Looper查看:
System.out.println("main Thread取..."+Looper.getLooper());
}
}
结果:
main Thread...null
main Thread取...Looper@17cb0a16
Thread-0...null
Thread-0取...Looper@37f2ae62