0%

ThreadLocal线程变量拷贝

文章字数:198,阅读全文大约需要1分钟

java.lang.ThreadLocal为每个线程提供不同的变量拷贝(线程变量)

和其他变量的区别

  1. 全局变量:属于类,类保存在堆中。属于所有线程共有的区域。所以全局变量能够被所有的线程访问到

  2. 局部变量:属于方法,方法存在栈空间,是线程私有的。但是方法的局部变量只属于方法,外部无法访问。

  3. ThreadLocal:属于线程,线程全局使用。一个ThreadLocal存储一个值

基本使用

1
2
3
4
5
6
ThreadLocal<String> tl = new ThreadLocal<String>;

tl.set("xxx");
tl.get();
//在线程结束的时候最好手动清除一下,提高回收效率
tl.remove();

案例

每个线程独立连接sql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.sql.Connection;  
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager {

private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
@Override
protected Connection initialValue() {
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "username",
"password");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
};

public static Connection getConnection() {
return connectionHolder.get();
}

public static void setConnection(Connection conn) {
connectionHolder.set(conn);
}
}