V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  gao6rich  ›  全部回复第 1 页 / 共 1 页
回复总数  2
329 天前
回复了 ffyyhh 创建的主题 MacBook 买 macbook air 好还是 pro 好
内存大的 air 吧
2022-12-12 19:17:59 +08:00
回复了 gao6rich 创建的主题 Java ThreadLocal
class ConnectionManager {
private Connection connect = null;

public Connection openConnection() {
if (connect == null) {
connect = DriverManager.getConnection();
}
return connect;
}

public void closeConnection() {
if (connect != null)
connect.close();
}
}

class Dao {
public void insert() {
ConnectionManager connectionManager = new ConnectionManager();
Connection connection = connectionManager.openConnection();

// 使用 connection 进行操作

connectionManager.closeConnection();
}
}
===========================================使用 ThreadLocal

public class ConnectionManager {

private static final ThreadLocal<Connection> dbConnectionLocal = new ThreadLocal<Connection>() {
@Override
protected Connection initialValue() {
try {
return DriverManager.getConnection("", "", "");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
};

public Connection getConnection() {
return dbConnectionLocal.get();
}
}
===========================================不使用 ThreadLocal

这两者有什么区别呢
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1007 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 22ms · UTC 20:01 · PVG 04:01 · LAX 12:01 · JFK 15:01
Developed with CodeLauncher
♥ Do have faith in what you're doing.