public class TestThreadLocal {
private static ThreadLocal<Integer> tl = new ThreadLocal<Integer>(){
protected Integer initialValue() {
return 0;
};
};
public int getNext() {
tl.set(tl.get() + 1);
return tl.get();
}
public static void main(String[] args) {
//线程共享testThreadLocal对象,此对象中有 ThreadLocal<Integer> tl
//ThreadLocal通过ThreadLocalMap为每个线程创建一个Integer对象的副本
TestThreadLocal testThreadLocal = new TestThreadLocal();
Thread thread1 = new Thread(new MyThread(testThreadLocal), "t1");
Thread thread2 = new Thread(new MyThread(testThreadLocal), "t2");
thread1.start();
thread2.start();
}
private static class MyThread implements Runnable {
private TestThreadLocal t;
public MyThread(TestThreadLocal t) {
this.t = t;
}
@Override
public void run() {
for(int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + "-" + t.getNext());
}
}
}
}
运行结果如下:
t1-1
t2-1
t1-2
t2-2
t1-3
t2-3
t2-1
t1-2
t2-2
t1-3
t2-3
可以看出,各个线程的局部变量的值互不干扰~