Threadlocal is not a thread, but a local variable of thread, and perhaps naming it as threadlocalvariable is easier to understand. Therefore, the code to write thread-local variables in Java is relatively clumsy, resulting in thread-local variables not being well-popularized in Java developers. Threadlocal interface method Threadlocal class interface is very simple, there are only 4 methods, let us first understand: void set (Object value) public void remove () Removes the value of the current thread local variable, The goal is to reduce the memory footprint.
the principle of threadlocalThere is a map in the Threadlocal class that is used to
A copy of the variable that stores each thread。 For example, the following sample implementation: public class threadlocalprivate Map values = Collections.synchronizedmap (new HashMap ());p ublic Object get () { Thread curthread = Thread.CurrentThread (), Object o = Values.get (Curthread), if (o = = null &&!values.containskey (c Urthread)) {o = InitialValue (); Values.put (Curthread, O);} Values.put (Thread.CurrentThread (), newvalue); return o;} Public Object InitialValue () {return null;}}
Demo Code
Public classThreadlocalexample { Public Static classMyrunnable implements Runnable {PrivateThreadlocal<integer> ThreadLocal =NewThreadlocal<integer>(); intLocal =0; @Override Public voidrun () {threadLocal.Set((int) (Math.random () *100D)); Local= (int) (Math.random () *100D); Try{Thread.Sleep ( -); } Catch(Interruptedexception e) {} System. out. println ("threadLocal:"+threadlocal.Get()); System. out. println ("Local:"+local); } } Public Static voidMain (string[] args) {myrunnable sharedrunnableinstance=Newmyrunnable (); Thread Thread1=NewThread (sharedrunnableinstance); Thread thread2=NewThread (sharedrunnableinstance); Thread1.start (); Thread2.start (); Try{thread1.join (); Thread2.join (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } //wait for the thread 1 to terminate//wait for the thread 2 to terminate }}
Differences between Java thread Local variables threadlocal and private variables