手撕ThreadLocal源码

首先,创建MyThreadLocal类,区分开java.lang.ThreadLocal

package com.huhu.threadlocal;

import java.util.HashMap;
import java.util.Map;

public class MyThreadLocal<T> {
    /**
     * 所有需要和当前线程绑定的数据要放到这个容器当中
     */
    private Map<Thread, T> 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<Connection> 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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值