The Looper class in Android uses Threadlocal to save each thread's Looper
Static final threadlocal<looper> sthreadlocal = new threadlocal<looper> ();
Simple understanding of the concept and use of threadlocal.
(i) Concept
Threadlocal provides a copy of the variable for each thread, which does not affect the independent thread.
(ii) Use
/** * threadlocal Usage test * * @author Peter_wang * @create-time 2014-12-24 pm 8:15:47 */public class Threadlocaldemo {private static Threadloca l<integer> num = new threadlocal<integer> () {//provides initialization, the initialization method is not implemented when the first use of Get () also requires initialization of the object protected Inte Ger InitialValue () {return 0; }; }; private static class Threadlocalthread extends Thread {@Override public void run () {for (int i = 0; i < 3; i++) {Num.set (Num.get () + 1); System.out.println ("Thread name is" + getName () + ", num is" + num.get ()); }}}/** * @param args */public static void main (string[] args) {Threadlocalthread Threa D1 = new Threadlocalthread (); Thread1.start (); Threadlocalthread thread2 = new Threadlocalthread (); Thread2.start (); }}
Operation Result:
Thread name is Thread-0,num is 1
Thread name is Thread-1,num is 1
Thread name is Thread-1,num is 2
Thread name is Thread-1,num is 3
Thread name is Thread-0,num is 2
Thread name is Thread-0,num is 3
(iii) use analysis
Both the threadlocal and thread synchronization mechanisms are designed to address the access violation of the same variable in multiple threads. Threadlocal provides variable copy, independent threads, high access efficiency, with "space for Time", thread synchronization mechanism for variable thread access mutual exclusion lock, variable multithreading sharing, access efficiency is low, processing is responsible, with "time for space".
Threadlocal is not used to solve variable thread-sharing security, but rather provides a way to save objects.
(iv) Source code analysis
View source code with THREADLOCAL.THREADLOCALMAP variable in each thread
Bind variables and thread through map in threadlocal
public void Set (T value) { Thread T = Thread.CurrentThread (); Get Threadlocalmap bind the thread and object variable threadlocalmap map = getmap (t); if (map! = null) Map.set (this, value); else createmap (t, value); }
Threadlocalmap Getmap (Thread t) { return t.threadlocals; }
Java-threadlocal Introduction