context

The use of ThreadLocal in java

Preface ThreadLocal is mainly used to store data for the current thread, this data is only accessible by the current thread. When defining a ThreadLocal, we can also define specific types of objects stored in the ThreadLocal. ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>(); Above we have defined a ThreadLocal object that stores an Integer. To store and get the object in ThreadLocal is also very simple, using get() and set(). threadLocalValue.set(1); Integer result = threadLocalValue.