public class T { ThreadLocal<Long> longLocal = new ThreadLocal<Long>(); public void set() { longLocal.set(Thread.currentThread().getId()); } public long getLong() { return longLocal.get(); } public static void main(String[] args) throws InterruptedException { final T test = new T(); test.set(); Thread thread1 = new Thread(){ public void run() { test.set(); System.out.println("線程一:"+test.getLong()); }; }; thread1.start(); thread1.join(); System.out.println("main線程:"+test.getLong()); System.out.println("沒有發生值的覆蓋,兩個線程保存的值是不一樣的"); } }
ThreadLocal.ThreadLocalMap threadLocals = null;
179 public void set(T value) { 180 Thread t = Thread.currentThread(); 181 ThreadLocalMap map = getMap(t); 182 if (map != null) 183 map.set(this, value); 184 else 185 createMap(t, value); 186 }
212 ThreadLocalMap getMap(Thread t) { 213 return t.threadLocals; 214 }
224 void createMap(Thread t, T firstValue) { 225 t.threadLocals = new ThreadLocalMap(this, firstValue); 226 }
328 ThreadLocalMap(ThreadLocal firstKey, Object firstValue) { 329 table = new Entry[INITIAL_CAPACITY]; 330 int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); 331 table[i] = new Entry(firstKey, firstValue); 332 size = 1; 333 setThreshold(INITIAL_CAPACITY); 334 }
416 private void set(ThreadLocal key, Object value) { 417 418 // We don't use a fast path as with get() because it is at 419 // least as common to use set() to create new entries as 420 // it is to replace existing ones, in which case, a fast 421 // path would fail more often than not. 422 423 Entry[] tab = table; 424 int len = tab.length; 425 int i = key.threadLocalHashCode & (len-1); 426 427 for (Entry e = tab[i]; 428 e != null; 429 e = tab[i = nextIndex(i, len)]) { 430 ThreadLocal k = e.get(); 431 432 if (k == key) { 433 e.value = value; 434 return; 435 } 436 437 if (k == null) { 438 replaceStaleEntry(key, value, i); 439 return; 440 } 441 } 442 443 tab[i] = new Entry(key, value); 444 int sz = ++size; 445 if (!cleanSomeSlots(i, sz) && sz >= threshold) 446 rehash(); 447 }
142 public T get() { 143 Thread t = Thread.currentThread(); 144 ThreadLocalMap map = getMap(t); 145 if (map != null) { 146 ThreadLocalMap.Entry e = map.getEntry(this); 147 if (e != null) 148 return (T)e.value; 149 } 150 return setInitialValue(); 151 }
271 static class Entry extends WeakReference<ThreadLocal> {
做者:jiajun 出處: http://www.cnblogs.com/-new/
本文版權歸做者和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。若是以爲還有幫助的話,能夠點一下右下角的【推薦】,但願可以持續的爲你們帶來好的技術文章!想跟我一塊兒進步麼?那就【關注】我吧。html