ThreadLocal用於保存某個線程共享變量:對於同一個static ThreadLocal,不一樣線程只能從中get,set,remove本身的變量,而不會影響其餘線程的變量bash
public class ThreadLocalTest {
public static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static String get() {
return threadLocal.get();
}
public static void set(String value) {
threadLocal.set(value);
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
final int j = i;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
ThreadLocalTest.set(j + "");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + ThreadLocalTest.get());
}
});
t.start();
}
}
}
複製代碼
結果:ide
經過上述示例 最主要的和最經常使用的就是get和set方法
先看set方法ui
public void set(T value) {
//獲取當前線程
Thread t = Thread.currentThread();
//獲取當前線程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null)
//若是map存在 直接設值
map.set(this, value);
else
//若是不存在,建立一個map並設置初始值
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
複製代碼
再看get方法this
public T get() {
//獲取當前線程
Thread t = Thread.currentThread();
//獲取當前線程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null) {
//若是ThreadLocalMap不爲null 經過map獲取對應的值
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
//若是沒有獲得對應的值,就初始化該ThreadLocal和對應的值
return setInitialValue();
}
private T setInitialValue() {
//初始化該ThreadLocal值
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
protected T initialValue() {
return null;
}
複製代碼
從源碼能夠看出,每一個線程都有本身的ThreadLocalMap,map裏面的key爲ThreadLocal,value爲對應的值,因此ThreadLocal在每一個線程中是互不干擾的,這樣同一個線程取到ThreadLocal裏面的值是同樣的,不一樣線程之間互不干擾,這樣就達到了同一個線程中值的傳遞spa