Threadlocal is equivalent to a map<thread, t> Each thread uses its own thread object Thread.CurrentThread () as the key to access the data, but Threadlocal is actually a wrapper over the map, And the thread can only access its own data and cannot manipulate data from other threads.
- T get ()
- Set (T)
- Remove ()
code example:
Public Static voidMain (string[] args) {string[] names=Newstring[]{"A", "B", "C", "D", "E"}; for(inti=0; i<names.length; i++){ FinalString MyName =Names[i]; NewThread () { Public voidrun () {name.set (myName); Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } test (); }}.start (); } /*Run Result: Thread-0, my name is a Thread-2, my name is C Thread-1, my name is "b Thread-3"- > My name is D Thread-4---My name is "E"*/}Private Staticthreadlocal<string> name =NewThreadlocal<string>(); Public Static voidTest () {System.out.println (Thread.CurrentThread (). GetName ()+ "-My Name" +name.get ());}
Multithreaded mapping tool-Thread local value