对ThreadLocal的理解
一个线程可以有多个threadLocal对象,在每个线程中都有多个独特的threadLocal对象,不与其他线程共享
参考链接
https://www.cnblogs.com/dolphin0520/p/3920407.html
demo代码
public class Test {
ThreadLocal<Long> longLocal = new ThreadLocal<Long>(){
protected Long initialValue() {
return Thread.currentThread().getId();
}
};
ThreadLocal<String> stringLocal = new ThreadLocal<String>(){;
protected String initialValue() {
return Thread.currentThread().getName();
}
};
public void set() {
longLocal.set(Thread.currentThread().getId());
stringLocal.set(Thread.currentThread().getName());
}
public long getLong() {
return longLocal.get();
}
public String getString() {
return stringLocal.get();
}
public static void main(String[] args) throws InterruptedException {
final Test test = new Test();
System.out.println(test.getLong());
System.out.println(test.getString());
Thread thread1 = new Thread(){
public void run() {
test.set();
System.out.println(test.getLong());
System.out.println(test.getString());
}
};
thread1.start();
thread1.join();
System.out.println(test.getLong());
System.out.println(test.getString());
}
get方法
public T get() {
Thread t = Thread.currentThread();//获取当前线程
ThreadLocalMap map = getMap(t);//获取map对象
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
//如果e为空的话,初始化
return setInitialValue();
}
getMap方法
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
ThreadLocalMap为ThreadLocal的内部类,k为当前对象,v为要副本值
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
setInitialValue方法
private T setInitialValue() {
T value = initialValue();//调用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 T initialValue() {
return null;
}