threadLocal是要解决什么问题?在什么应用场景下使用呢

2025-03-07 01:29:30
推荐回答(2个)
回答1:

ThreadLocal 实例通常是类中的私有静态字段,一般用于存储与线程关联的局部变量。
这是个DB工具类,看明白你就知道了。

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

public class DB {
private static DataSource ds;
private static ThreadLocal threadLocal = new ThreadLocal();
static {
ds = new ComboPooledDataSource();
}
//防止实例
private DB(){
}
public static DataSource getDataSource() {
return ds;
}
/***
* 从连接池获取conn连接
* @return
*/
public static Connection getConnection() {
try {
// 得到当前线程上绑定的连接
Connection conn = threadLocal.get();
if (conn == null) { // 代表线程上没有绑定连接
conn = ds.getConnection();
threadLocal.set(conn);
}
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/***
* 开启事务
*/
public static void beginTransaction() {
try {
// 得到当前线程上绑定连接开启事务
Connection conn = getConnection();
if(!conn.getAutoCommit()){
logger.warn(" connection got the last autoCommit value ! ");
}
conn.setAutoCommit(false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 提交事务
*/
public static void commitTransaction() {
try {
Connection conn = threadLocal.get();
if (conn != null) {
conn.commit();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}

/***
* 关闭连接
*/
public static void closeConnection() {
try {
Connection conn = threadLocal.get();
if (conn != null) {
conn.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
threadLocal.remove();
}
}
/***
* 关闭连接
*/
public static void rollback() {
try {
Connection conn = threadLocal.get();
if (conn != null) {
conn.rollback();;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

回答2:

ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了线程保持对象的方法和避免参数传递的方便的对象访问方式

ThreadLocal的应用场合,最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。