Threadlocal is proposed to solve the concurrency problem of multithreaded routines, which can be called thread-local variables. The difference from a general variable is that the lifecycle is within the thread range.
The static variable is the same life cycle as the class, that is, the static variable exists as long as the class exists.
What would a static threadlocal be like?
Look at one of the following examples,
public class SequenceNumber {private static threadlocal<integer> Seqnum = new threadlocal<integer> () {public Integer InitialValue () {return 0;}}; public int Getnextnum () {Seqnum.set (Seqnum.get () + 1), return Seqnum.get (), public static void Main (string[) args) {sequ Encenumber sn = new SequenceNumber (); testclient T1 = new TestClient (SN); TestClient t2 = new TestClient (SN); testclient t3 = new TestClient (SN); T1.start (); T2.start (); T3.start (); T1.print (); T2.print (); T3.print (); private static class TestClient extends thread{private sequencenumber sn; public testclient (SequenceNumber sn) {this. sn = SN; public void Run () {for (int i=0; i< 3; i++) {System.out.println (Thread.CurrentThread (). GetName () + "-->" + sn.ge Tnextnum ()); } public void Print () {for (int i=0; i< 3; i++) {System.out.println (Thread.CurrentThread (). GetName () + "-->" + S N.getnextnum ()); } } } }
Here's the result.
Thread-2--> 1 Thread-2--> 2 Thread-2--> 3 Thread-0--> 1 Thread-0--> 2 Thread-0--> 3 Thread-1 ; 1 Thread-1--> 2 Thread-1--> 3 main--> 1 main--> 2 main--> 3 main--> 4 main--> 5 main--> 6 Main--> 7 main--> 8 main--> 9
You can see that the static threadlocal variable is a thread-related static variable, in which a static variable is referenced by each instance, but within a thread, the static variable is separated