The threadlocal differs from the thread member variable, threadlocal This class provides a thread-local variable. This local variable is not the same as the general member variable, threadlocal variables are used by multiple threads, each thread can only get a copy of the variable, which is described in the Java API, through the Reading API source code, found not a copy, what concept of replica? A clone? Or something else, too vague.
To be exact, the registry (map<thread,t>) of the threadlocal type of variable has changed, but the threadlocal type of the variable itself is indeed one, which is the essence!
Here's an example:
One, standard example
Define the Mythreadlocal class, create one of its object TLT, respectively, to four threads, the result of four threads TLT variable does not appear a common phenomenon, the second is the use of each, which means that four threads use a copy of the TLT (clones).
/**
* Use threadlocal class
*
* @author leizhimin 2010-1-5 10:35:27
*/
public class Mythreadlocal {
//defines a ThreadLocal variable to hold int or Integer data
Private threadlocal<integer> TL = new ThreadLocal <Integer> () {
@Override
protected Integer initialvalue () {
return 0;
}
};
Public Integer Getnextnum () {
///to fetch the value of TL by 1 and update the value of setting T1
Tl.set (tl.get () + 1);
return Tl.get ();
}
}
/**
* Test Thread
*
* @author leizhimin 2010-1-5 10:39:18
*/
public class Testthread extends thread {
Private mythreadlocal TLT = new mythreadlocal ();
Public Testthread (mythreadlocal tlt) {
This.tlt = TLT;
@Override
public void Run () {
for (int i = 0; i < 3; i++) {
System.out.println (Thread.CurrentThread (). GetName () + "T" + tlt.getnextnum ());
}
}
}
/**
* ThreadLocal测试
*
* @author leizhimin 2010-1-5 10:43:48
*/
public class Test {
public static void main(String[] args) {
MyThreadLocal tlt = new MyThreadLocal();
Thread t1 = new TestThread(tlt);
Thread t2 = new TestThread(tlt);
Thread t3 = new TestThread(tlt);
Thread t4 = new TestThread(tlt);
t1.start();
t2.start();
t3.start();
t4.start();
}
}