ThreadLocal理解:
This class provides thread-local variables. These variables differ from * their normal counterparts in that each thread that accesses one (via its * <tt>get</tt> or <tt>set</tt> method) has its own, independently initialized * copy of the variable. <tt>ThreadLocal</tt> instances are typically private * static fields in classes that wish to associate state with a thread (e.g., * a user ID or Transaction ID).
* <p>Each thread holds an implicit reference to its copy of a thread-local * variable as long as the thread is alive and the <tt>ThreadLocal</tt> * instance is accessible; after a thread goes away, all of its copies of * thread-local instances are subject to garbage collection (unless other * references to these copies exist).
就是说,对于threadlocal的变量,每一个线程都会拷贝一个该变量的副本,每个线程操作的都是这个副本,在一个线程销毁后,这些副本也会被垃圾回收.
如下例:
public class ThreadLocalTest extends Thread {
private int i = 0;
@Override
public void run() {
i=3;
System.out.println("次线程"+i);
}
public static void main(String args[]) throws Exception{
ThreadLocalTest threadLocalTest = new ThreadLocalTest();
threadLocalTest.start();
Thread.sleep(2000);
System.out.println("主线程"+threadLocalTest.i);
}
}
结果:
可以看到,主线程和次线程输出i的值都为3
加上threadlocal后:
public class ThreadLocalTest extends Thread {
private ThreadLocal<Integer> local = new ThreadLocal<Integer>();
@Override
public void run() {
local.set(3);
System.out.println("次线程"+local.get());
}
public static void main(String args[]) throws Exception{
ThreadLocalTest threadLocalTest = new ThreadLocalTest();
threadLocalTest.local.set(1);
threadLocalTest.start();
Thread.sleep(2000);
System.out.println("主线程"+threadLocalTest.local.get());
}
}
结果:
可以看到主线程和次线程拿到的值都是自己设置的值,所以threadlocal的变量再运行时,会进行拷贝.
从上面可以看到,使用threadlocal不存在共享变量的,也就是说它不是作为同步机制