Content from, Zhang Xiaoxiang teacher's Zhang Xiaoxiang-java multi-threading and concurrent Library Advanced Application Video tutorial
Package Com.lipeng;public class MyThreadLocalTest2 {private final static mythreadlocal<string> Mythreadlocal=new Mythreadlocal<string> ();/** * @param args */public static void main (string[] args) {new Thread () {public void run () { Threadlocaldata.getthreadlocaldata (). Setage (12); Threadlocaldata.getthreadlocaldata (). SetName ("Zhang San"); System.out.println (Thread.CurrentThread (). GetName () + "----------------" +a.getname ()); System.out.println (Thread.CurrentThread (). GetName () + "----------------" +b.getname ());}. Start (); new Thread () {public void run () {Threadlocaldata.getthreadlocaldata (). Setage (18); Threadlocaldata.getthreadlocaldata (). SetName ("John Doe"); System.out.println (Thread.CurrentThread (). GetName () + "----------------" +a.getname ()); System.out.println (Thread.CurrentThread (). GetName () + "----------------" +b.getname ());}. Start ();} Static class A{public static String GetName () {return Threadlocaldata.getthreadlocaldata (). GetName (); public static void SetName (String name) {mythreadlocal.set (name);}}Static class B{public static String GetName () {return Threadlocaldata.getthreadlocaldata (). GetName (); public static void SetName (String name) {mythreadlocal.set (name);}}} Class Threadlocaldata{private static threadlocal<threadlocaldata> threadlocal=new threadlocal< Threadlocaldata> ();p rivate String name;private int age;private threadlocaldata () {//does not provide public construction method, only provides a static factory method, This method returns an instance object of the current class that is related to the current thread. }public static Threadlocaldata Getthreadlocaldata () {threadlocaldata threadlocaldata=threadlocal.get (); Threadlocaldata==null) {threadlocaldata=new threadlocaldata (); Threadlocal.set (threadlocaldata);} return threadlocaldata;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}} <span style= "White-space:pre" ></span> when we get a thread bound object, we don't want to see threadlocal, but instead directly get the object bound to the current thread, here, The constructor of a thread-bound class is private, providing a static method that allows the object to be obtained from this class, and this method is a get from thradlocal even if the current thread is bound to an instance.
Java Multi-Threading and concurrency Applications-(5)-How to use the Threadlocal class gracefully