In programming, we define method parameters to pass variable content, if the execution method level is deep, then each method needs to define the parameters to be passed, at this time, some variables can be passed through ThreadLocal, as long as all methods are executed on the same thread, the value of ThreadLocal can be set and read.
The ThreadLocal class is used to provide local variables inside the thread. When these variables are accessed (get/set) in a multi-threaded environment, the variables in each thread are relatively independent of the variables in other threads.
ThreadLocal will first get the current thread (Thread t = Thread.currentThread()) when executing the set method, and use the current thread to get a ThreadLocalMap, if the map is not empty, it means that the current thread has a previously bound map, then update the value of this map, if not, use itself as the key to put the value in the map, so as to realize the binding of variables and threads.
Test the code, set the thread pool to maintain a maximum of 5 threads, and when we call the ThreadLocal get method in the case of multi-threading, we will get the ThreadLocal data (Data set by other threads), usThe ThreadLocal set method is not called on the current thread to set the data, as shown in the figure below:
Error causes:Once a thread is reused, it is likely that the first value obtained from ThreadLocal is a value left over from other previous threads。
Because, after we finish with ThreadLocal on the current thread,Be sure to call remove for timely purge。 As shown below:
Code:
(End)
|