1. ThreadLocal的解釋,參見
http://my.oschina.net/u/1989867/blog/528047
2. ThreadLocal的簡單應用:利用ThreadLocal隔離局部變量的特色實現爲每一個線程提供本身的數據庫連接
ConnectionResource.java ------------------------------------------產生數據庫連接的資源類
package com.lxh.ThreadLocal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// 資源類
public class ConnectionResource {
// 屬性
public static String userName = "root";
public static String userPass = "admin123";
public static String url = "jdbc:mysql://localhost:3306/user";
public static String driverName = "com.mysql.jdbc.Driver";
// 獲取數據庫連接
public Connection getConnection(){
Connection conn = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url, userName, userPass);
} catch (SQLException e) {
System.out.println("獲取數據庫連接失敗..."+e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("獲取數據庫加載類失敗..."+e.getMessage());
e.printStackTrace();
}
return conn;
}
}
ConnectionThread.java ------------------------------------------模擬多個線程實現屢次獲取數據庫連接
package com.lxh.ThreadLocal;
import java.sql.Connection;
//
public class ConnectionThread implements Runnable {
//
public ThreadLocal<Connection> tl = new ThreadLocal<Connection>() {
@Override
protected Connection initialValue() {
ConnectionResource cr = new ConnectionResource();
return cr.getConnection();
}
};
@Override
public void run() {
// 連接對象
Connection conn = null;
// 循環獲取線程的連接對象
for (int i = 0; i < 5; i++) {
conn = tl.get();
System.out.println("***當前線程【" + Thread.currentThread().getName()
+ "】獲取的連接資源:" + conn + "***");
}
}
}
Test.java ------------------------------------------測試類
package com.lxh.ThreadLocal;
/**
* 使用ThreadLocal解決多線程問題
*/
public class Test {
public static void main(String[] args) {
ConnectionThread ct = new ConnectionThread();
Thread t0 = new Thread(ct);
Thread t1 = new Thread(ct);
Thread t2 = new Thread(ct);
Thread t3 = new Thread(ct);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
3. 測試結果
![](http://static.javashuo.com/static/loading.gif)
4. 測試結果分析 咱們經過"測試結果"能夠清晰地看到,同一個線程,不管請求多少次,其獲取到的數據庫連接都是同樣的,這符合咱們的預期----不讓同一個線程獲取多個數據庫連接以減小資源消耗。