简述ThreadLocal

简述ThreadLocal

线程安全

字面意思,ThreadLocal为本地线程,ThreadLocal是一个线程内部的存储类,可以在指定线程内存储数据,数据存储之后,只有指定线程可以访问存储的数据

所以说,ThreadLocal是线程安全的,因为每一个ThreadLocal都是相互隔离的,我们再从源码分析一波:

 /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

ThreadLocalMap是ThreadLocal的一个内部类,这里将this作为key存入了map中;

/**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

取的时候,也是将this传进去获取数据的,所以可以看出来,ThreadLocal的线程安全;

那么ThreadLocal和Synchronized有啥区别呢?

Synchronized是将对象锁住,以线程等待的方式解决访问冲突;而ThreadLocal直接将每个线程进行隔离,以牺牲空间的方式解决访问冲突。

使用

初始化:

private ThreadLocal<Student> studentMap = new TransmittableThreadLocal<>();

set数据:

private Student stu = new Studen();
stu.setName("小明");
stu.setAge(12);
studentMap.set(stu);

get数据:

Student student = studentMap.get();
System.out.println(student.getName());

注意:由于ThreadLocal内部是将this作为key值放进map里的,所以,一个线程的一个ThreadLocal对象只能存一个值,一般常用于系统当前用户的登录信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值