Java ThreadLocal static?

前端 未结 5 956
独厮守ぢ
独厮守ぢ 2020-12-23 10:43

Setting a value in Thread Local:

//Class A holds the static ThreadLocal variable.

    Class A{

    public static ThreadLocal myThreadLocal = new T         


        
5条回答
  •  Happy的楠姐
    2020-12-23 11:08

    I study the java source code,

    1. java.lang.Thread Class contains a instance variable as below.

      ThreadLocal.ThreadLocalMap threadLocals = null;

    Because threadLocals variable is non-static, Every thread in a application (i.e., every instance of Thread Class) will have it's own copy of threadLocals map.

    1. Key for this map is, current ThreadLocal instance, and value is the value which you pass as argument to ThreadLocal.set().

    2. When you try to fetch value as ThreadLocal.get() , internally, it will fetch from the ThreadLocalMap of Current Thread.

    In simple terms, you are getting & setting values from/to your current Thread Object, not from/to your ThreadLocal object.

提交回复
热议问题