Java ThreadLocal static?

前端 未结 5 954
独厮守ぢ
独厮守ぢ 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 11:08

    Multiple threads executing B's someBMethod, will end up updating the SAME A's static ThreadLocal variable myThreadLocal

    Yes, they operate on the same object. However, it is important to realize that the way ThreadLocal works is that each thread has its own, separate value. Thus if you have ten threads writing to myThreadLocal and then reading from myThreadLocal, each will see the correct (i.e. their own) value.

    To put it another way, it does not matter which class or object writes to an instance of ThreadLocal. What matters is the thread in whose context the operation is performed.

提交回复
热议问题