首先介紹一下兩個方法:數據庫
1.經過Map進行實現spa
主鍵爲Thread ,value 爲數據,線程
主要思路爲:與線程綁定,不一樣的線程之間的數據相互獨立
blog
2.經過ThreadLocal 實現get
首先先介紹一下ThreadLocal 的原理源碼
每一個Thread ,都有一個ThreadLocalMap ,因此每次經過ThreadLocal .get的時候,至關因而在當前線程的ThreadLocalMap 查查找 key爲 ThreadLocal(調用者)的value值。it
這個是ThreadLocal get方法的源碼io
ThreadLocal的主要應用場景:ast
1.用來解決數據庫鏈接、Session管理class
private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() { public Connection initialValue() { return DriverManager.getConnection(DB_URL); } }; public static Connection getConnection() { return connectionHolder.get(); }
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; }
2.第二個場景用於:
線程多實例,須要保存分離每一個線程的數據