Last active
September 5, 2017 08:15
-
-
Save Aitozi/b00acb2a383ce85b8c22fc0ecb404252 to your computer and use it in GitHub Desktop.
Threadlocal的用法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*当我们调用get方法的时候,其实每个当前线程中都有一个ThreadLocal。每次获取或者设置都是对该ThreadLocal进行的操作,是与其他线程分开的 | |
*应用场景:当很多线程需要多次使用同一个对象,并且需要该对象具有相同初始化值的时候最适合使用ThreadLocal | |
*/ | |
public class ConnectionUtil { | |
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); | |
private static Connection initConn = null; | |
static { | |
try { | |
initConn = DriverManager.getConnection("url, name and password"); | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
} | |
} | |
public Connection getConn() { | |
Connection c = tl.get(); | |
if(null == c) tl.set(initConn); | |
return tl.get(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment