/*
* @author zhangxiaomin
* @email 1396729865@qq.com
*/
public class HelloWorld{
static ThreadLocal<String> threadLocal = new ThreadLocal<>(){{
this.set("main");
}};
public static void main(String[] args) {
System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
Thread zhangxiaomin,zhangsan;
(zhangxiaomin = new Thread(()->{
System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
threadLocal.set("zhangxiaomin");
System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
},"zhangxiaomin")).start();
(zhangsan = new Thread(()->{
System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
threadLocal.set("zhangsan");
System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
},"zhangsan")).start();
}
}
-
接著執(zhí)行一下。
- 問(wèn)題來(lái)了?為毛線(xiàn)zhangxiaoomin和zhangsan這個(gè)線(xiàn)程首先打印出來(lái)的是一個(gè)null呢? 這個(gè)ThreadLocal不應(yīng)該是一個(gè)共享變量嗎?這三個(gè)線(xiàn)程不應(yīng)該都保持一致嘛?
- 下一步看一下ThreadLocal的源碼(請(qǐng)注意看我的注釋?zhuān)?/li>
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
* 第一步先看這個(gè)方法。返回了一個(gè)線(xiàn)程的內(nèi)部對(duì)象。而且看下邊的調(diào)用,傳遞的都是Thread.CurrentThread().
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
* 第二步:ThreadLocal調(diào)用set方法的時(shí)候。創(chuàng)建了一個(gè)新的對(duì)象并且賦值
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
createMap(t, value);
}
}
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
* 下邊的代碼是考慮到是用initialValue()初始化ThreadLocal的數(shù)據(jù)。明顯使用了延遲加載的方式。
* @return the current thread's value of this thread-local
*/
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();
}
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
*
* @return the initial value
*/
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);
}
if (this instanceof TerminatingThreadLocal) {
TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
}
return value;
}
-
總結(jié):使用ThreadLocal變量本質(zhì)上操作的是當(dāng)前線(xiàn)程的內(nèi)部變量ThreadLocalMap
/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
/**
* Construct a new map including all Inheritable ThreadLocals
* from given parent map. Called only by createInheritedMap.
*
* @param parentMap the map associated with parent thread.
*/
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (Entry e : parentTable) {
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
- 接下來(lái)的問(wèn)題就本質(zhì)了:知道這個(gè)東西有什么用呢??
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。