下面經過一個例子來證實經過ThreadLocal能達到在每一個線程中建立變量副本的效果:java
public class TestThreadLocal { public static ThreadLocal<String> threadLocal = new ThreadLocal<>(); public static void main(String []args){ threadLocal.set("hello world"); Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("thread:"+threadLocal.get()); } }); thread.start(); System.out.println("main:"+threadLocal.get()); } }
控制檯輸出:數據庫
main:hello world thread:null
ThreadLocal相關類圖結構:ide
Thread類中有一個ThreadLocalMap類型的變量threadLocals。threadLocals用來存儲實際的變量副本,key爲當前ThreadLocal變量,value爲變量副本。線程
初始化時,在Thread中threadLocals變量爲null,只有當前線程第一次調用Thread的set()或get()方法thread中threadLocal進行初始化,而且以當前ThreadLocal變量爲key,以ThreadLocal要保存的副本變量爲value,存到threadLocals。若是要獲取副本變量,經過ThreadLocal的get方法。code
ThreadLocal最多見的使用場景是用來解決數據庫鏈接、Session管理等。blog