The Threadlocal class, which represents a thread-local variable, lets each thread create a copy of the variable by placing the data in the threadlocal. It can also be viewed as another way of threading synchronization by creating a thread-local copy of a variable for each thread, thereby avoiding conflicts when concurrent threads read and write to the same variable resource at the same time.
Examples are as follows:
Import Java.util.Random;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.TimeUnit;
Import Com.sun.javafx.webkit.Accessor; public class Threadlocaltest {static class Threadlocalvariableholder {private static threadlocal<integer> value
= new Threadlocal<integer> () {private Random Random = new Random ();
Protected synchronized Integer InitialValue () {return random.nextint (10000);
}
};
public static void Increment () {Value.set (Value.get () + 1);
public static int Get () {return value.get ();
} static class accessor implements runnable{private final int id;
public accessor (int id) {this.id = ID; @Override public void Run () {while!
Thread.CurrentThread (). isinterrupted ()) {threadlocalvariableholder.increment ();
System.out.println (this);
Thread.yield (); @Override public String toString () {return "#" + ID+ ":" + threadlocalvariableholder.get ();
} public static void Main (string[] args) {Executorservice executorservice = Executors.newcachedthreadpool ();
for (int i = 0; i < 5; i++) {Executorservice.execute (new accessor (i));
try {TimeUnit.MICROSECONDS.sleep (1);
catch (Interruptedexception e) {e.printstacktrace ();
} executorservice.shutdownnow ();
}
}
Run Result:
#1:9685
#1:9686
#2:138
#2:139 #2:140 #2: #0:
5255
...
From the results of the operation, each thread is used for its own local variables, and read and write each other.
Threadlocal provides a total of three methods to operate, Set,get and remove.
In Android, Looper uses threadlocal to create separate Looper objects for each thread.
Public final class Looper {
private static final String TAG = "Looper";
Sthreadlocal.get () would return null unless for you ' ve called prepare ().
Static final threadlocal<looper> sthreadlocal = new threadlocal<looper> ();
private static void Prepare (Boolean quitallowed) {
if (sthreadlocal.get ()!= null) {
throw new runtimeexception ("Only one looper could created per thread");
}
Sthreadlocal.set (New Looper (quitallowed));
}
When a thread needs its own looper and message queues, it calls Looper.prepare (), which creates the Looper object and MessageQueue for the thread that belong to the thread, and saves the Looper object in Threadlocal.