1. 程式人生 > >Java併發程式設計ThreadLocal

Java併發程式設計ThreadLocal

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不存在共享變數的,也就是說它不是作為同步機制