public class ThreadLocal<T> extends Object
该类提供了线程局部变量.这些变量不同于它们的普通对应物.因为访问一个变量(通过其 get 或 set 方法)的每个线程都有自己的局部变量,它独立于变量的初始化副本.ThreadLocal 实例通常是类中的私有静态字段它们希望将状态与某一个线程(例如,用户 ID 或事务 ID)相关联。
public ThreadLocalTest() ... {} ;
// 通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
private static ThreadLocal < Integer > seqNum = new ThreadLocal < Integer > () ... {
protected Integer initialValue() ...{
return 0;
}
} ;
// 获取下一个序列值
public int getNextNum() ... {
seqNum.set(seqNum.get()+1);
return seqNum.get();
}
public static void main(String[] args) ... {
ThreadLocalTest test = new ThreadLocalTest();
// 3个线程共享sn,各自产生序列号
TestClient client1 = new TestClient(test);
TestClient client2 = new TestClient(test);
TestClient client3 = new TestClient(test);
client1.start();
client2.start();
cl
private ThreadLocalTest test;
/** *//**
* 构造函数.
*/
public TestClient() ...{};
/** *//**
* 构造函数.
*/
public TestClient(ThreadLocalTest test) ...{
this.test = test;
};
@Override
public void run() ...{
//{④每个线程打出3个序列值
for(int i=0 ; i<=3 ; i++) ...{
System.err.println("[currentThread name:>>]" +Thread.currentThread().getName() + "===NextNum is:==" +test.getNextNum());
}
}
}
}
结果
========================
[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
========================
通常我们通过匿名内部类的方式定义ThreadLocal的子类.
考察输出的结果信息,我们发现每个线程所产生的序号虽然都共享同一个ThreadLocalTest实例但它们并没有发生相互干扰的情况,而是各自产生独立的序列号,这是因为我们通过ThreadLocal为每一个线程提供了单独的副本。