Threadlocal is proposed to solve the concurrent problem of multi-threaded programs. It can be called a thread local variable. The difference from common variables is that the life cycle is within the thread range.
Static variables have the same life cycle as the class, that is, as long as the class exists, static variables also exist.
So what is a static threadlocal?
Let's look at the following example,
Public class sequencenumber {</P> <p> Private Static threadlocal <integer> seqnum = new threadlocal <integer> () {<br/> Public integer initialvalue () {<br/> return 0; <br/>}< br/>}; </P> <p> Public int getnextnum () {<br/> seqnum. set (seqnum. get () + 1); <br/> return seqnum. get (); <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> sequencenumber Sn = new sequencenumber (); <br/> testclient T1 = new testclient (SN); <br/> testclient t2 = new testclient (SN); <br/> testclient T3 = new testclient (SN ); </P> <p> t1.start (); <br/> t2.start (); <br/> t3.start (); </P> <p> t1.print (); <br/> t2.print (); <br/> t3.print (); </P> <p >}</P> <p> Private Static class testclient extends thread {<br/> private sequencenumber Sn; <br/> Public testclient (sequencenumber Sn) {<br/> This. sn = Sn; <br/>}</P> <p> Public void run () {<br/> for (INT I = 0; I <3; I ++) {<br/> system. out. println (thread. currentthread (). getname () + "-->" + Sn. getnextnum (); <br/>}</P> <p> Public void print () {<br/> for (INT I = 0; I <3; I ++) {<br/> system. out. println (thread. currentthread (). getname () + "-->" + Sn. getnextnum (); <br/>}</P> <p >}< br/>
The result is as follows:
Thread-2 --> 1 <br/> thread-2 --> 2 <br/> thread-2 --> 3 <br/> thread-0 --> 1 <br/> thread-0 --> 2 <br/> thread-0 --> 3 <br/> thread-1 --> 1 <br/> thread-1 --> 2 <br/> thread-1 --> 3 <br/> main --> 1 <br/> main --> 2 <br/> main --> 3 <br/> main --> 4 <br /> main --> 5 <br/> main --> 6 <br/> main --> 7 <br/> main --> 8 <br/> main --> 9 </ p> <p>
It can be found that the static threadlocal variable is a static variable related to the thread, that is, within a thread, the static variable is referenced by each instance, but within different threads, static variables are separated.