手撕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

ps 图灵课堂老师从近一百套最新一线互联网公司面试题中精选而出,涵盖Java架构面试 所有技术栈,包括JVM,Mysql,并发,Spring,Redis,MQ,Zookeeper,Netty, Dubbo,Spring Boot,Spring Cloud,数据结构与算法,设计模式等相关技术领域的大 厂面试题及详解。 详情咨询客服获取全套面经试题。

上一篇 适配器模式改造Servlet
下一篇 文件字符流

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: