ThreadLocal,從表面上讀英文的意思爲線程本地變量,這樣也許更好理解了,就是每一個線程本身獨有的,不與其它線程共享的變量。
經常使用的就這幾個,倆內部類,四個方法。java
舉例:數據庫
定義兩個不一樣任務的線程,分別向各自的本地變量中存放值,見證兩個線程本地變量中的內容是互不干擾的。ide
public class MyThreadLocal { // 採用匿名內部類的方式來重寫initialValue方法 private static final ThreadLocal<Object> threadLocal = new ThreadLocal<Object>() { /** * ThreadLocal沒有被當前線程賦值時或當前線程剛調用remove方法後調用get方法,返回此方法值 */ @Override protected Object initialValue() { System.out.println("調用get方法時,當前線程共享變量沒有設置,調用initialValue獲取默認值!"); return null; } }; // 操縱int類型的任務線程 public static class MyIntegerTask implements Runnable { private String name; MyIntegerTask(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { // ThreadLocal.get方法獲取線程變量 if (null == MyThreadLocal.threadLocal.get()) { // ThreadLocal.et方法設置線程變量 MyThreadLocal.threadLocal.set(0); System.out.println("線程" + name + ": 0"); } else { int num = (Integer) MyThreadLocal.threadLocal.get(); MyThreadLocal.threadLocal.set(num + 1); System.out.println("線程" + name + ": " + MyThreadLocal.threadLocal.get()); if (i == 3) { MyThreadLocal.threadLocal.remove(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } // 操縱string類型的任務線程 public static class MyStringTask implements Runnable { private String name; MyStringTask(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { if (null == MyThreadLocal.threadLocal.get()) { MyThreadLocal.threadLocal.set("a"); System.out.println("線程" + name + ": a"); } else { String str = (String) MyThreadLocal.threadLocal.get(); MyThreadLocal.threadLocal.set(str + "a"); System.out.println("線程" + name + ": " + MyThreadLocal.threadLocal.get()); } try { Thread.sleep(800); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { new Thread(new MyIntegerTask("IntegerTask1")).start(); new Thread(new MyStringTask("StringTask1")).start(); } }
運行結果:
調用get方法時,當前線程共享變量沒有設置,調用initialValue獲取默認值! 線程IntegerTask1: 0 調用get方法時,當前線程共享變量沒有設置,調用initialValue獲取默認值! 線程StringTask1: a 線程StringTask1: aa 線程IntegerTask1: 1 線程StringTask1: aaa 線程IntegerTask1: 2 線程StringTask1: aaaa 線程IntegerTask1: 3 線程StringTask1: aaaaa 調用get方法時,當前線程共享變量沒有設置,調用initialValue獲取默認值! 線程IntegerTask1: 0
涉及到的源碼:性能
get();方法:供ThreadLocal對象來調用測試
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(); }
getMap();方法:這個方法是返回當前線程t中的一個成員變量threadLocals,它是Thread類中的一個內部類this
ThreadLocal.ThreadLocalMap threadLocals = null; ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
看一下ThreadLocalMap的實現:能夠看到ThreadLocalMap的Entry繼承了WeakReference(弱引用類),而且使用ThreadLocal做爲鍵值。spa
static class ThreadLocalMap { static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } } 。。。。。。。。。 }
getEntry();方法線程
private Entry getEntry(ThreadLocal<?> key) { int i = key.threadLocalHashCode & (table.length - 1); Entry e = table[i]; if (e != null && e.get() == key) return e; else return getEntryAfterMiss(key, i, e); }
setInitialValue();方法:就是若是map不爲空,就設置鍵值對,爲空,再建立Mapcode
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); return value; }
createMap();方法:若是map爲空,就初始化ThreadLocalMap對象
void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
不難看出,get()方法,首先獲取當前的線程,而後經過getMap(t)方法獲取到一個map,map的類型爲ThreadLocalMap。而後接着下面獲取到<key,value>鍵值對,若是獲取成功,則返回value值,若是map爲空,則調用setInitialValue方法返回value。
測試完上面的例子,看完get方法的實現,應該明白ThreadLocal是怎麼個原理了,大體以下(就是這樣的):首先,在每一個線程Thread內部有一個ThreadLocal.ThreadLocalMap類型的成員變量threadLocals,這個threadLocals就是用來存儲實際的變量的,鍵值爲當前ThreadLocal變量,value爲變量(好比說上面定義的String變量或者Integer變量)。初始時,在Thread裏面,threadLocals爲空,當經過ThreadLocal變量調用get()方法或者set()方法,就會對Thread類中的threadLocals進行初始化,而且以當前ThreadLocal變量爲鍵值,以ThreadLocal要保存的變量爲value,存到threadLocals。若是要使用副本變量,就能夠經過get方法在threadLocals裏面查找。
這種存儲結構的好處:
最多見的ThreadLocal使用場景爲 用來解決 數據庫鏈接、Session管理等。
好比如下,代碼來自:https://www.iteye.com/topic/1...
private static final ThreadLocal threadSession = new ThreadLocal(); public static Session getSession() throws InfrastructureException { Session s = (Session) threadSession.get(); try { if (s == null) { s = getSessionFactory().openSession(); threadSession.set(s); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } return s; }
通常有兩種方法: