Introduction to java-ThreadLocal
The logoff class in android uses ThreadLocal to save the Logoff of each thread.
Static final ThreadLocal SThreadLocal = new ThreadLocal ();
Briefly understand the concept and use of ThreadLocal.
(1) Concepts
ThreadLocal provides a copy of the variable for each thread. The variable threads are independent of each other.
(2) Use
/*** ThreadLocal usage test ** @ author peter_wang * @ create-time 8:15:47 */public class ThreadLocalDemo {private static ThreadLocal
Num = new ThreadLocal
() {// Provides initialization. When you use get () for the first time, you also need to initialize the object protected Integer 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 thread1 = new ThreadLocalThread (); thread1.start (); threadLocalThread thread2 = new ThreadLocalThread (); thread2.start ();}}
Running 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
(3) Use Analysis
ThreadLocal and thread synchronization mechanisms are designed to solve the access conflict between the same variables in multiple threads. ThreadLocal provides variable copying, independent threads, high access efficiency, and "space for Time". The thread synchronization mechanism locks inter-thread access to variables, shares multiple threads of variables, and has low access efficiency, responsible for handling, with "Time for Space ".
ThreadLocal is not used to secure Variable Thread sharing, but to save objects.
(4) Source Code Analysis
View the source code. Each Thread contains the ThreadLocal. ThreadLocalMap variable.
Bind variables to threads through map in ThreadLocal
Public void set (T value) {Thread t = Thread. currentThread (); // obtain ThreadLocalMap to bind the Thread to the object variable ThreadLocalMap map = getMap (t); if (map! = Null) map. set (this, value); else createMap (t, value );}
ThreadLocalMap getMap(Thread t) { return t.threadLocals; }