手写ThreadLocal
package com.bjpowernode.ThreadLocal;
import java.util.HashMap;
import java.util.Map;
public class MyThreadLocal<T>
{
private Map<Thread,T> map = new HashMap<>();
public void set(T o)
{
//向threadLocal中绑定
//因为我们一个线程运行的时候,必定在一个栈里面,一定是当前线程
//所以直接存就可以了
map.put(Thread.currentThread(),o);
}
public T get()
{
//从threadLocal中获取
return map.get(Thread.currentThread());
}
public void remove()
{
//从threadLocal中删除
map.remove(Thread.currentThread());
}
}
ThreadLocal改造工具类
package com.bjpowernode.ThreadLocal;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class DBUtil
{
private static MyThreadLocal<Connection> local = new MyThreadLocal();
private static ResourceBundle resourceBundle = ResourceBundle.getBundle("resources.jdbc");
private static String url = resourceBundle.getString("url");
private static String username = resourceBundle.getString("user");
private static String password = resourceBundle.getString("password");
private static String driver = resourceBundle.getString("driver");
static
{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws SQLException
{
Connection connection = local.get();
if(connection == null)
{
//第一次调用一定是空的
connection = new Connection();
//绑定
local.set(connection);
}
return connection;
}
}
Dao层
package com.bjpowernode.ThreadLocal;
import java.sql.SQLException;
public class UserDao
{
public void Insert()
{
// Thread thread = Thread.currentThread();
// System.out.println(thread);
try {
Connection connection = DBUtil.getConnection();
System.out.println(connection);
} catch (SQLException e) {
throw new RuntimeException(e);
}
System.out.println("UserDao添加");
}
}
Service层
package com.bjpowernode.ThreadLocal;
import java.sql.SQLException;
public class UserService
{
private UserDao userDao = new UserDao();
public void Save()
{
// Thread thread = Thread.currentThread();
// System.out.println(thread);
try {
Connection connection = DBUtil.getConnection();
System.out.println(connection);
} catch (SQLException e) {
throw new RuntimeException(e);
}
userDao.Insert();
System.out.println("UserService保存");
}
}
Conn对象
package com.bjpowernode.ThreadLocal;
public class Connection
{
}
测试类
package com.bjpowernode.ThreadLocal;
public class Test
{
public static void main(String[] args)
{
//创建获取Conn对象
// Thread thread = Thread.currentThread();
// System.out.println(thread);
// Connection connection = new Connection();
UserService userService = new UserService();
userService.Save();
}
}
标签:Web,JAVA,Thread,ThreadLocal,connection,源码,static,new,public
From: https://blog.51cto.com/u_16322355/8097422