Java ThreadLocal 解析

package concurrent;
/*
* @author: wjf
* @version: 2016年3月27日 下午2:44:46
*/

public class TestThreadLocal {
    /*
     * threadLocal 會爲線程創建一個共享變量的本地副本,這樣的話,可以在線程內部任意使用,而又不影響其他線程,這樣一來就不會產生線程安全問題,
     * 也不會嚴重影響性能,但是有一點:使用 threadLocal 肯定需要耗費更大的內存
     */
    /*
     * threadLocal 重寫 initialValue 方法,就可以不用調用 set() 方法,否則如果不調用 set 方法的話,initialValue
     * 方法默認返回 null
     */
    ThreadLocal<Long> locall=new ThreadLocal<Long>(){
        protected Long initialValue(){
            return Thread.currentThread().getId();
        }
    };
    ThreadLocal<String> locals=new ThreadLocal<String>(){
        protected String initialValue(){
            return Thread.currentThread().getName();
        }
    };
    public void set(){
        locall.set(Thread.currentThread().getId());
        locals.set(Thread.currentThread().getName());
    }
    public void get(){
        System.out.println(locall.get());
        System.out.println(locals.get());
    }
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        final TestThreadLocal test=new TestThreadLocal();
//      test.set();
        test.get();
        Thread thread1=new Thread(){
            public void run(){
                test.set();
                test.get();
            }
        };
        thread1.start();
        thread1.join();
        test.get();


    }

}
發佈了40 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章