“ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本
对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式。前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响”
本示例如果不使用ThreadLocal,static的变量会被三个线程一同操作最后三个线程操作后,最后的值为9.
使用ThreadLocal后,每个线程有一个自己的static变量,打印出来是三个线程的static变量会变成3.
public class ThreadLocalDemo {
private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {
// 覆盖初始化方法
public Integer initialValue() {
return 0;
}
};
// 下一个序列号
public int getNextNum() {
seqNum.set(seqNum.get() + 1);
return seqNum.get();
}
private static int test;
// 下一个序列号
public int getNextNumTest() {
test++;
return test;
}
private static class TestClient extends Thread {
private ThreadLocalDemo sn;
public TestClient(ThreadLocalDemo sn,String threadName) {
this.sn = sn;
setName(threadName);
}
// 线程产生序列号
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("thread[" + Thread.currentThread().getName()
+ "] sn[" + sn.getNextNum() + "]");
}
}
//没有使用ThreadLocal
/*public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("thread[" + Thread.currentThread().getName()
+ "] sn[" + sn.getNextNumTest() + "]");
}
}*/
}
public static void main(String[] args) {
ThreadLocalDemo sn = new ThreadLocalDemo();
// 三个线程产生各自的序列号
TestClient t1 = new TestClient(sn,"Thread t1");
TestClient t2 = new TestClient(sn,"Thread t2");
TestClient t3 = new TestClient(sn,"Thread t3");
t1.start();
t2.start();
t3.start();
}
}