As the name suggests, ThreadLocal is used to support the variables of thread-local. It has the following features:
ThreadLocal is global for the same thread. You can get the value of ThreadLocal anywhere in the thread. For example, set the value of ThreadLocal in function A and obtain the value in function B.
For other threads, ThreadLocal is local. You cannot do this: set the value of ThreadLocal in thread A and obtain this value in thread B.
The ThreadLocal class has only three member functions:
Protected Object initialValue ()-returns the initial value of the ThreadLocal variable. In the first-line process, if get () is called before set (), initialValue () will be called only once. If set () has been called before get (), initialValue () will not be called.
Public Object get ()-get the value of the ThreadLocal variable (for the current thread ).
Public void set (Object value)-set the value of the ThreadLocal variable (for the current thread ).
Usage:
When you need to port a single-threaded program to a multi-threaded environment, you can package some global variables with ThreadLocal to achieve thread security. But do not abuse ThreadLocal: You set A ThreadLocal in function A and use this ThreadLocal in function B, which means that B depends on.
Note:
From the JDK source code, the actual value is obtained based on the ThreadLocal reference during get, so do not change the ThreadLocal reference between set () and get, for example, a new ThreadLocal is created.
[Java]
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 ();
}
Example of an error: In A multi-threaded environment, if the call sequence is thread A, call setValue (oa), thread B, call setValue (ob), and thread A calls getValue (), then a null value is obtained. Because the tl reference has changed.
[Java]
Public class ThreadLocalTest {
Static ThreadLocal tl = null;
Public static void setValue (Object o ){
Tl = new ThreadLocal ();
Tl. set (o );
} Www.2cto.com
Public static Object getValue (){
Return tl. get ();
}
}
Author: huxiweng