一、ThreadLocal是什么?
ThreadLocal与线程同步机制不同,线程同步机制是多个线程共享同一个变量,而ThreadLocal是为每一个线程创建一个单独的变量副本,故而每个线程都可以独立地改变自己所拥有的变量副本,而不会影响其他线程所对应的副本。可以说ThreadLocal为多线程环境下变量问题提供了另外一种解决思路。
二、ThreadLocal常用方法的源码
1、set()方法
//set操作,为线程绑定变量
public void set(T value) {
Thread t = Thread.currentThread();//1.首先获取当前线程对象
ThreadLocalMap map = getMap(t);//2.获取该线程对象的ThreadLocalMap
if (map != null)
map.set(this, value);//如果map不为空,执行set操作,以当前threadLocal对象为key,实际存储对象为value进行set操作
else
createMap(t, value);//如果map为空,则为该线程创建ThreadLocalMap
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;//线程对象持有ThreadLocalMap的引用
}
//线程t.threadLocals定义
ThreadLocal.ThreadLocalMap threadLocals = null;
1. `ThreadLocal`仅仅是个变量访问的入口;
2. 每一个`Thread对象`都有一个`ThreadLocalMap对象`;
2、get()方法
public T get() {
Thread t = Thread.currentThread();//1.首先获取当前线程
ThreadLocalMap map = getMap(t);//2.获取线程的map对象
if (map != null) {//3.如果map不为空,以threadlocal实例为key获取到对应Entry,然后从Entry中取出对象即可。
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();//如果map为空,也就是第一次没有调用set直接get(或者调用过set,又调用了remove)时,为其设定初始值
}
private T setInitialValue() {
T value = initialValue();//获取初始值
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
//initialValue方法,默认是null,访问权限是protected,即允许重写。
protected T initialValue() {
return null;
}
三、使用示例
public class SeqCount {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
// 实现initialValue()
public Integer initialValue() {
return 0;
}
};
public int nextSeq(){
threadLocal.set(threadLocal.get() + 1);
return threadLocal.get();
}
public static void main(String[] args) {
SeqCount seqCount = new SeqCount();
//每个线程里map的key都一样(threadLocal实例为同一个)
SeqThread thread1 = new SeqThread(seqCount);
SeqThread thread2 = new SeqThread(seqCount);
SeqThread thread3 = new SeqThread(seqCount);
SeqThread thread4 = new SeqThread(seqCount);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
private static class SeqThread extends Thread {
private SeqCount seqCount;
SeqThread(SeqCount seqCount) {
this.seqCount = seqCount;
}
public void run() {
for(int i = 0 ; i < 3 ; i++){
System.out.println(Thread.currentThread().getName() + " seqCount :" + seqCount.nextSeq());
}
}
}
}
//执行结果
Thread-0 seqCount :1
Thread-0 seqCount :2
Thread-0 seqCount :3
Thread-2 seqCount :1
Thread-2 seqCount :2
Thread-2 seqCount :3
Thread-1 seqCount :1
Thread-1 seqCount :2
Thread-1 seqCount :3
Thread-3 seqCount :1
Thread-3 seqCount :2
Thread-3 seqCount :3
四、Thread、ThreadLocal、ThreadLocalMap关系图
每个thread中都存在一个map,map的类型是
ThreadLocal.ThreadLocalMap
。Map中的key为一个threadlocal实例(引用)。
五、应用场景
ThreadLocal在spring的事务管理,包括Hibernate的session管理等都有出现,在web开发中,有时会用来管理用户会话 HttpSession,web交互中这种典型的一请求一线程的场景比较适合使用ThreadLocal。