ThreadLocal 你究竟是個什麼鬼

 

    不少文章都拿它跟同步機制做比較,我以爲這個思路對於理解這個東西徹底沒有做用。java

ThreadLocal跟synchronize這類東西做比較,是不少文章的套路,我感受這麼比較,就跟比較重載跟重寫的區別,final跟finally的區別同樣,越比較越混亂。二者關注的方向壓根都不一樣。session

   ThreadLocal的應用場合,我以爲最適合的是按線程多實例(每一個線程對應一個實例)的對象的訪問,而且這個對象不少地方都要用到dom

    這個是我以爲解釋ThreadLocal最好的總結,ide

    session的例子特別能夠說明問題,一個線程對應一個session,在執行的過程中可能不少地方都要獲取session中的值,若是在編寫代碼的過程中,一直把session當作一個傳參數,在方法中或者對象間各類傳遞,也不是不能夠,可是這代碼得是有多難看。可是使用TreadLocal的話,代碼就簡便了不少。並且還有很好的隔離性。因此ThreadLocal是一種編寫代碼的思路,可是並非只能採用這種方式才行。最後抄個例子,簡單的說明下這個東東怎麼用。this

package test;  
  
import java.util.Random;  
  
class Student {  
    private int age;  
  
    public int getAge() {  
        return age;  
    }  
  
    public void setAge(int age) {  
        this.age = age;  
    }  
}  
  
public class TestThreadLocal implements Runnable {  
  
    ThreadLocal studentLocal = new ThreadLocal();  
  
    public static void main(String[] args) {  
        TestThreadLocal t = new TestThreadLocal();  
        new Thread(t, "t1").start();  
        new Thread(t, "t2").start();  
    }  
  
    @Override  
    public void run() {  
        accessStudent();  
    }  
  
    private void accessStudent() {  
        Student s = this.getStudent();  
        Random random = new Random();  
        int age = random.nextInt(100);  
        System.out.println("current thread set age " + Thread.currentThread()  
                + ":" + age);  
        s.setAge(age);  
        System.out.println("current thread first get age "  
                + Thread.currentThread() + ":" + s.getAge());  
        try {  
            Thread.sleep(500);  
        } catch (InterruptedException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        System.out.println("current thread second get age "  
                + Thread.currentThread() + ":" + s.getAge());  
    }  
  
    public Student getStudent() {  
        Student s = (Student) studentLocal.get();  
        if (s == null) {  
            s = new Student();  
            studentLocal.set(s);  
        }  
        return s;  
    }  
}