public class threadlocal<t> extends Object
This class provides thread-local variables. These variables are different from their normal counterparts. Because each thread that accesses a variable (through its Get or set method) has its own local variable, which is independent of the initialization copy of the variable. ThreadLocal instances are usually private static fields in a class they want to associate a state with a thread (for example, a user ID or a transaction ID).
Public Threadlocaltest () ... {} ;
Override the Threadlocal InitialValue () method with an anonymous inner class, specifying the initial value
private static ThreadLocal < integer > seqnum = new ThreadLocal < integer > () ... {
Protected Integer initialvalue () ... {
return 0;
}
} ;
Get Next sequence value
public int getnextnum () ... {
Seqnum.set (Seqnum.get () +1);
return Seqnum.get ();
}
public static void Main (string[] args) ... {
Threadlocaltest test = new Threadlocaltest ();
3 threads share sn, each generating serial number
TestClient client1 = new testclient (test);
TestClient client2 = new testclient (test);
TestClient client3 = new testclient (test);
Client1.start ();
Client2.start ();
CL public class TestClient extends Thread ... {
Private threadlocaltest test;
/** *//**
* constructor.
*/
Public TestClient () ... {};
/** *//**
* constructor.
*/
Public testclient (threadlocaltest test) ... {
This.test = test;
};
@Override
public void run () ... {
{④ 3 sequence values per thread
for (int i=0; i<=3 i++) ... {
System.err.println ("[CurrentThread Name:>>]" +thread.currentthread () getName () + "===nextnum is:==" + Test.getnextnum ());
}
}
} ient3.start ();
}
Results
========================
[CurrentThread Name:>>] Thread-0===nextnum is:==1
[CurrentThread Name:>>] Thread-0===nextnum is:==2
[CurrentThread Name:>>] Thread-0===nextnum is:==3
[CurrentThread Name:>>] Thread-0===nextnum is:==4
[CurrentThread Name:>>] Thread-1===nextnum is:==1
[CurrentThread Name:>>] Thread-1===nextnum is:==2
[CurrentThread Name:>>] Thread-1===nextnum is:==3
[CurrentThread Name:>>] Thread-1===nextnum is:==4
[CurrentThread Name:>>] Thread-2===nextnum is:==1
[CurrentThread Name:>>] Thread-2===nextnum is:==2
[CurrentThread Name:>>] Thread-2===nextnum is:==3
[CurrentThread Name:>>] Thread-2===nextnum is:==4
========================
Usually we define subclasses of threadlocal by way of anonymous inner classes.
After examining the output information, we find that each thread produces a sequence number that shares the same threadlocaltest instance but does not interfere with each other, but instead produces separate serial numbers. This is because we provide a separate copy of each thread through the threadlocal.