ThreadLocal解析

1、ThreadLocal解决了什么问题?

答:同线程内数据传参的问题,在开发中有时我们想将某一对象的引用在同一线程中多处使用,大家都知道在Thread类中,是有map的,也就是说每个Thread都有自己的context,查看下Thread源码:

/* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

我们大可通过此 map来将我们自己的对象设置在其中,但是我们也不得不每次获取当前Thread对象,然后从当前线程对象中获取map,然后为对象取定一个key值,把对象做为value放置在其中,这在代码上太麻烦了,如果我们有一个工具类就好了,因此ThreadLocal诞生了。记住,它仅仅只是一个工具类罢了,并没有起到实质性的作用,有了它我们的代码将变的简介。


至于很多同学理解的它能解决同一对象的多线程并发访问问题,那纯属扯淡!


2、ThreadLocal如何帮我们将对象放置在Thread的threadLocals中的?

废话少说,直接贴出JDK源码:

/**
     * 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);
    }

我们看到先获取当前线程对象,然后获取map,然后将threadlocal对象本身做为key,目标对象做为value设置进入map就ok了,如此简单

至于map的set方法我们也可以看一下:

/**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
整个set的过程其实就是一个数组实现hash算法的过程,对value值并没有做clone动作,这点很重要,这也意味着同一对象实质上可被多个Thread对象引用,并没有做到本质上的ThreadLocal。

也就是说,当你想要将对象设置进入Thread中的map中时,你需要先有一个对应的threadlocal对象。两个线程使用两个threadlocal对象对同一个对象(如:person对象)管理也是ok的,此时两个线程共享该对象。

想要获取刚刚设置的对象时,调用threadlocal对象的get()方法即可,以下是JDK源码

/**
     * 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)
                return (T)e.value;
        }
        return setInitialValue();
    }

以this为key获取对象


3、警告

多个线程仍然可以通过不同的treadlocal对象将同一个对象(如Person对象)设置在不同Thread的map中,此时多个线程共享该person对象。ThreadLocal只是一个工具而已。


4、实例

package com.wanyonghui.learn;

public class ThreadLocalLearn {
	
	private static ThreadLocal<Person> tl = new ThreadLocal<Person>();
	
	public static void func(){
		
		Person p2 = (Person)tl.get();
		
		System.out.println(p2.getName());
	}
	
	
	public static void main(String[] args) {
		
		Person p = new Person();
		p.setName("wanyonghui");
		tl.set(p);
		
		func();
		
		Thread t = new Thread();
		
	}
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值