Threadlocal's core idea is simple: provide a copy of a variable for each individual thread.
The Java-provided synchronized keyword uses a "sync lock" mechanism to block threads from competing access, which means "space for time". : "10PT; Font-size:> threadlocal Use the "copy copy" way, everyone has a share, you use your, I use my, we do not affect each other, is "space for time." When each thread modifies a variable, it actually modifies a copy of the variable, not afraid of affecting other threads.
To deepen the understanding of threadlocal, let me use an example to illustrate how threadlocal isolates variable access and modification between threads:
"1" Serialnum class
Package example.thread.threadLocal;
public class Serialnum {
private static int nextserialnum = 1;
@SuppressWarnings ("Unchecked")
private static ThreadLocal Serialnum = new ThreadLocal () {
Protected synchronized Object InitialValue () {
return new Integer (nextserialnum++);
}
};
public static int Get () {
Return ((Integer) (Serialnum.get ())). Intvalue ();
}
@SuppressWarnings ("Unchecked")
public static void Set (Integer newserial) {
Serialnum.set (newserial);
}
}
"2" Getserialnumthread
package example.thread.threadLocal;
public class Getserialnumthread implements Runnable {
public static void Main (String args[]) {
Getserialnumthread serialnumgetter = new Getserialnumthread ();
Thread T1 = new Thread (serialnumgetter, "thread A");
Thread t2 = new Thread (serialnumgetter, "thread B");
T1.start ();
try {
T1.join ();
catch (Interruptedexception e) {
E.printstacktrace ();
}
T2.start ();
}
public void Run () {
int myserialnum = Getserialnum ();
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName ()
+ "The serial number obtained is" + myserialnum);
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName ()
+ "modified serial number is" + (Myserialnum * 3));
Setserialnum (Myserialnum * 3);
System.out.println ("thread" + thread.currentthread (). GetnamE ()
+ "The again obtained serial number is" + getserialnum ());
}
Private int getserialnum () {
return serialnum.get ();
private void setserialnum (int newserialnum) {
Serialnum.set (new Integer (Newserialnum));
}
}
The results of the operation are as follows:
Thread thread A gets a serial number that is 1
Thread A modified the serial number to 3
Thread A again gets the serial number is 3
Thread thread B Gets a serial number of 2
Threads thread B modifies the serial number of 6
The serial number obtained again by thread thread B is 6