当前位置: 首页 > 图灵资讯 > 技术篇> 手撕ThreadLocal源码

手撕ThreadLocal源码

来源:图灵教育
时间:2023-05-21 09:22:53

1.图解72

手撕ThreadLocal源码_ThreadLocal

2.代码72com中的代码.powernode.threadlocalTest

package com.powernode.threadlocal;///这里是主main方法  72public class Test {    public static void main(String[] args) {        ///获得Thread对象        Thread thread = Thread.currentThread();        System.out.println(thread);                ///调用servicece        UserService userService = new UserService();        userService.save();    }}

UserService

package com.powernode.threadlocal;///service类  72public 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类  72public 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集合存储conection对象  72public 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;//conection  72public class Connection {}

DBUtil

package com.powernode.threadlocal;//工具类  72public class DBUtil {    ///静态变量特性,类加载时执行,而且只执行一次    ////全局大Map集合    private  static MyThreadLocal local = new MyThreadLocal<>();    ///每次都用这种方法获取Conection对象    public static Connection getConnection(){        Connection connection = local.get();        if(connection==null){            ///第一次调用getconection方法时,connectin一定是空的            ///空的new一次            connection = new Connection();            ////将newconection对象绑定到Map集合中            local.set(connection);        }        return connection;    }}

手撕ThreadLocal源码_数据_02