剛學習完java,對如今這塊還不是很瞭解.由於作的項目比較小,因此對Thread接觸的不是不少,偶爾在網上看看相關資料,也沒有去特地深入的瞭解,之前看篇文章說ThreadLocal是解決多線程共享數據的一個很好的方法,主要是對數據進行了共享,爲每一個線程都建立了這個變量的副本,知道後來要用到相關Thread的知識,就去看了下源碼,感受有點不對,就到網上又找了些資料看看,最後看這篇文章才感受之前理解都是錯的 http://www.iteye.com/topic/103804.java
ThreadLocal並非爲每一個變量的副原本解決多線程共享數據的.而是數據共享並非ThreadLocal來管理的,而是經過ThreadLocalMap這個對象來管理的,每一個線程都有一個屬於本身的ThreadLocalMap,當咱們想操做一個變量的時候,咱們要調用ThreadLocal.set()方法.咱們經過這段代碼能夠看出來多線程
public void set(T value) { 學習
Thread t = Thread.currentThread(); this
ThreadLocalMap map = getMap(t); spa
if (map != null) 線程
map.set(this, value); 對象
else get
createMap(t, value); 源碼
} it
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
當咱們在多線程裏面操做一個變量的時候,先取到當前線程,而後根據當前線程獲取他的ThreadLocalMap對象,若是爲null的話就new一個ThreadLocalMap並把ThreadLocal做爲key,想賦值給這個變量的值做爲value.而後當咱們獲取這個變量的值的時候
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
return (T)map.get(this);
// Maps are constructed lazily. if the map for this thread
// doesn't exist, create it, with this ThreadLocal and its
// initial value as its only entry.
T value = initialValue();
createMap(t, value);
return value;
}
先獲取當前線程,而後在獲取這個線程的
ThreadLocal只是做爲一個key值ThreadLocalMap對象,在根據ThreadLocal獲取這個變量的值.因此咱們在多線程裏面操做一個成員變量的時候.咱們能夠把這個成員變量讓ThreadLocal來管理.