1. 图解 72
2. 代码 72
代码在com.powernode.threadlocal
Test
package com.powernode.threadlocal;
//这里是主main方法 72
public class Test {
public static void main(String[] args) {
//获取Thread对象
Thread thread = Thread.currentThread();
System.out.println(thread);
//调用service
UserService userService = new UserService();
userService.save();
}
}
UserService
package com.powernode.threadlocal;
//一个service类 72
public class UserService {
private UserDao userDao = new UserDao();
//提供一个方法
public void save(){
//获取Thread对象
Thread thread = Thread.currentThread();
System.out.println(thread);
//得到connection
Connection connection = DBUtil.getConnection();
System.out.println(connection);
//调用UserDao中的insert方法
userDao.insert();
}
}
UserDao
package com.powernode.threadlocal;
//一个Dao类 72
public class UserDao {
public void insert(){
//获取Thread对象
Thread thread = Thread.currentThread();
System.out.println(thread);
//得到connection
Connection connection = DBUtil.getConnection();
System.out.println(connection);
System.out.println("User Dao insert");
}
}
MyThreadLocal
package com.powernode.threadlocal;
import java.util.HashMap;
import java.util.Map;
//这个类负责使用map集合存储connection对象 72
public class MyThreadLocal {
//所有需要和当前线程绑定的数据要放到这个容器中
private Map map = new HashMap<>();
//向ThreadLocal中绑定数据
public void set(T obj){
map.put(Thread.currentThread(),obj);
}
//从ThreadLocal中获取数据
public T get(){
return map.get(Thread.currentThread());
}
//移除ThreadLocal当中的数据
public void remove(){
map.remove(Thread.currentThread());
}
}
Connection
package com.powernode.threadlocal;
//connection类 72
public class Connection {
}
DBUtil
package com.powernode.threadlocal;
//工具类 72
public class DBUtil {
//静态变量特点,类加载时执行,并且只执行一次
//全局大Map集合
private static MyThreadLocal local = new MyThreadLocal<>();
//每次都调用这个方法来获取Connection对象
public static Connection getConnection(){
Connection connection = local.get();
if(connection==null){
//第一次调用getConnection方法的时候,connectin一定是空的
//空的就new一次
connection = new Connection();
//将new的connection对象绑定到Map集合中
local.set(connection);
}
return connection;
}
}
标签:Thread,Connection,connection,ThreadLocal,源码,new,com,public
From: https://blog.51cto.com/u_15784725/6317337