Multi-thread ing tool-local thread value and local multi-thread ing thread
ThreadLocal is equivalent to a Map <Thread, T>. Each Thread uses its own Thread object Thread. currentThread () is used as the key to access data, but ThreadLocal is actually a packaged Map, and the thread can only access its own data, and cannot operate on the data of other threads.
- T get ()
- Set (T)
- Remove ()
Sample Code:
Public static void main (String [] args) {String [] names = new String [] {"A", "B", "C", "D ", "E"}; for (int I = 0; I <names. length; I ++) {final String myName = names [I]; new Thread () {public void run () {name. set (myName); try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace () ;}test ();}}. start ();}/* running 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 static ThreadLocal <String> name = new ThreadLocal <String> (); public static void test () {System. out. println (Thread. currentThread (). getName () + "-> my name is" + name. get ());}