Threadlocal can define thread-scoped variables, or thread-local variables. The difference from a general variable is that the life cycle is within the scope of the thread.
That is, an object of a class (for a clear description, hereinafter referred to as a object) has a threadlocal variable,
Then each thread is opened, and the first call to the A object will initialize the value of the variable and will not affect the A object in the other thread. The test is as follows:
Public Interface IBase { publicstaticfinalnew threadlocal<boolean>() { protected Boolean InitialValue () { returnfalse; } };}
Public class Implements IBase {}
The real test class:
Public classTestclassname { Public Static voidMain (string[] args) {Baseimpl Baseimpl=NewBaseimpl (); FinalIBase base =(IBase) Baseimpl; Base.onlyCallLocalFlg.get (); //System.out.println (Base.onlyCallLocalFlg.get ());System.out.println (Base.getclass (). getinterfaces () [0].getsimplename ()); System.out.println (Base.getclass (). Getsimplename ()); NewThread () { Public voidrun () {Base.onlyCallLocalFlg.set (true); }}.start (); Base.onlyCallLocalFlg.set (true); NewThread () { Public voidrun () {System.out.println ("In Thread:" +base.onlyCallLocalFlg.get ()); }}.start (); System.out.println ("Main thread:" +base.onlyCallLocalFlg.get ()); }}
Printing results:
IBase
Baseimpl
Main thread: True
In Thread: false
It can be concluded that the second thread will not be affected by the first thread being created or by modifying the value of the ONLYCALLLOCALFLG in the main path.
Tips:
The static variable is the same life cycle as the class, that is, as long as the class exists, then the static variable exists.
So what would a static threadlocal be like?
The threadlocal variable of static is a thread-related static variable, that is, within a thread, the static variable is referenced by each instance, but the static variable is separated in different threads.
Usage and testing of thread variables (ThreadLocal)