使用线程封闭是实现线程安全最简单的方式之一,维持线程封闭性的一种常规方法是使用 ThreadLocal,它能使线程中的某个值与保存值的对象关联起来。ThreadLocal 提供了 get 与 set 等方法,这些方法为每个使用该变量的线程都有一份独立的副本,因此 get 总是返回由当前执行线程在调用 set 时设置的最新值。
public class Thread implements Runnable {
// ......
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
// ......
}
public class ThreadLocal<T> {
// ......
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
private Entry[] table;
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
// ......
tab[i] = new Entry(key, value);
// ......
}
// ......
}
// ......
}
ThreadLocal 在对 ThreadLocal.ThreadLocalMap 进行封装之后,对外提供了 get 和 set 方法。
public class ThreadLocal<T> {
// ......
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);
}
// ......
}