ThreadLocal 的内部类。是以 ThreadLocal 的 hash 值为数组下标, Entry 元素为值的数组。ThreadLocalMap 内部是实现了一个类似 Map 的映射关系,内部的 Entry 继承自 WeakReference<ThreadLocal<?>> ,它持有ThreadLocal的弱引用,保存 ThreadLocal.set(value) 传入的 value 。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
复制代码
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
复制代码
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
复制代码
public class Main {
static final ThreadLocal<String> mThreadLocal = new ThreadLocal<>();
public static void main(String[] args) {
new Thread("thread1") {
@Override
public void run() {
mThreadLocal.set("value1");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(currentThread().getName() + " localValue:" + mThreadLocal.get());
}
}.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread("thread2") {
@Override
public void run() {
mThreadLocal.set("value2");
System.out.println(currentThread().getName() + " localValue:" + mThreadLocal.get());
}
}.start();
}
}
复制代码
输出:
thread2 localValue:value2 thread1 localValue:value1 复制代码
虽然是同一个 ThreadLocal对象 ,而且都调用的同样的 set get 方法,但是 get 方法返回的值,一定是与当前线程对应的。