ThreadLocal 概述 ThreadLocal實例僅作為線程局部變數的==操作類==,以及==線程存儲局部變數時的Key==。真正的線程局部變數是存儲在各自線程的本地,通過Thread類中的 進行存儲。 若希望線上程本地存儲多個局部變數需要使用多個ThreadLocal實例進行操作。 Thre ...
ThreadLocal
概述
ThreadLocal實例僅作為線程局部變數的==操作類==,以及==線程存儲局部變數時的Key==。真正的線程局部變數是存儲在各自線程的本地,通過Thread類中的ThreadLocal.ThreadLocalMap threadLocals
進行存儲。
若希望線上程本地存儲多個局部變數需要使用多個ThreadLocal實例進行操作。
ThreadLocal源碼示例
set(T v)方法
通過Thread.currentThread()獲取當前的線程實例,然後獲取當前線程實例里的ThreadLocal.ThreadLocalMap threadLocals
,若不存在該集合對象則創建。最後,將當前ThreadLocal實例作為Key,將參數值v存儲當前線程的threadLocals
集合中。即var3.set(this, var1);
get()方法
通過Thread.currentThread()獲取當前的線程實例,然後獲取當前線程實例里的ThreadLocal.ThreadLocalMap threadLocals
,若該集合對象不為空,則用當前ThreadLocal實例作為Key,從集合對象中獲取之前存儲的值。即var3 = var2.getEntry(this);
public T get() {
Thread var1 = Thread.currentThread();
ThreadLocal.ThreadLocalMap var2 = this.getMap(var1);
if (var2 != null) {
ThreadLocal.ThreadLocalMap.Entry var3 = var2.getEntry(this);
if (var3 != null) {
Object var4 = var3.value;
return var4;
}
}
return this.setInitialValue();
}
private T setInitialValue() {
Object var1 = this.initialValue();
Thread var2 = Thread.currentThread();
ThreadLocal.ThreadLocalMap var3 = this.getMap(var2);
if (var3 != null) {
var3.set(this, var1);
} else {
this.createMap(var2, var1);
}
return var1;
}
public void set(T var1) {
Thread var2 = Thread.currentThread();
ThreadLocal.ThreadLocalMap var3 = this.getMap(var2);
if (var3 != null) {
var3.set(this, var1);
} else {
this.createMap(var2, var1);
}
}
public void remove() {
ThreadLocal.ThreadLocalMap var1 = this.getMap(Thread.currentThread());
if (var1 != null) {
var1.remove(this);
}
}
ThreadLocal.ThreadLocalMap getMap(Thread var1) {
return var1.threadLocals;
}
void createMap(Thread var1, T var2) {
var1.threadLocals = new ThreadLocal.ThreadLocalMap(this, var2);
}
Thread源碼示例
Thread類使用ThreadLocal.ThreadLocalMap threadLocals
集合對象盛裝線程局部變數。
public class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
private volatile String name;
private int priority;
private Thread threadQ;
private long eetop;
/* Whether or not to single_step this thread. */
private boolean single_step;
/* Whether or not the thread is a daemon thread. */
private boolean daemon = false;
/* JVM state */
private boolean stillborn = false;
/* What will be run. */
private Runnable target;
/* The group of this thread */
private ThreadGroup group;
/* The context ClassLoader for this thread */
private ClassLoader contextClassLoader;
/* The inherited AccessControlContext of this thread */
private AccessControlContext inheritedAccessControlContext;
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;