首先,创建MyThreadLocal类,区分开java.lang.ThreadLocal
- package com.huhu.threadlocal;
-
- import java.util.HashMap;
- import java.util.Map;
-
- public class MyThreadLocal
{ - /**
- * 所有需要和当前线程绑定的数据要放到这个容器当中
- */
- private Map
map = new HashMap<>(); -
- /**
- * 向ThreadLocal中绑定数据
- */
- public void set(T obj) {
- map.put(Thread.currentThread(), obj);
- }
-
- /**
- * 从ThreadLocal中获取数据
- *
- * @return
- */
- public T get() {
- return map.get(Thread.currentThread());
- }
-
- /**
- * 移除ThreadLocal当中的数据
- */
- public void remove() {
- map.remove(Thread.currentThread());
- }
- }
接着,分别创建Connection类和DBUtil类
- package com.huhu.threadlocal;
-
- public class Connection {
- }
- package com.huhu.threadlocal;
-
- public class DBUtil {
- //静态变量特点:类加载时执行,并且只执行一次
- private static MyThreadLocal
local=new MyThreadLocal<>(); -
- /**
- * 调用方法获取Connection对象
- * @return
- */
- public static Connection getConnection(){
- Connection connection=local.get();
- if (connection==null){
- //第一次调用方法肯定为null,new一个
- connection=new Connection();
- //将new出来的Connection对象绑定到Map集合中
- local.set(connection);
- }
- return connection;
- }
-
- }
然后创建UserDao类和UserService类
- package com.huhu.threadlocal;
-
- public class UserDao {
- public void insert() {
- Thread thread=Thread.currentThread();
- System.out.println(thread);
- Connection connection = DBUtil.getConnection();
- System.out.println(connection);
- System.out.println("User Dao insert...");
- }
- }
- package com.huhu.threadlocal;
-
- public class UserService {
- private UserDao userDao = new UserDao();
-
- public void save() {
- Thread thread=Thread.currentThread();
- System.out.println(thread);
- Connection connection = DBUtil.getConnection();
- System.out.println(connection);
- userDao.insert();
- }
- }
最后,创建测试Test类
- package com.huhu.threadlocal;
- //张三发送请求,对应一个线程t1
- //李四发送请求,对应一个线程t2
- public class Test {
- public static void main(String[] args) {
- Thread thread=Thread.currentThread();
- System.out.println(thread);
- //Connection connection=new Connection();
-
- UserService userService=new UserService();
- userService.save();
- }
- }
