2019獨角獸企業重金招聘Python工程師標準>>>
?
????很多文章都拿它跟同步機制作比較,我覺得這個思路對于理解這個東西完全沒有作用。
ThreadLocal跟synchronize這類東西作比較,是很多文章的套路,我感覺這么比較,就跟比較重載跟重寫的區別,final跟finally的區別一樣,越比較越混亂。兩者關注的方向壓根都不同。
? ?ThreadLocal的應用場合,我覺得最適合的是按線程多實例(每個線程對應一個實例)的對象的訪問,并且這個對象很多地方都要用到
? ? 這個是我覺得解釋ThreadLocal最好的總結,
? ? session的例子特別可以說明問題,一個線程對應一個session,在執行的過程當中可能很多地方都要獲取session中的值,如果在編寫代碼的過程當中,一直把session當做一個傳參數,在方法中或者對象間各種傳遞,也不是不可以,但是這代碼得是有多難看。但是使用TreadLocal的話,代碼就簡便了很多。而且還有很好的隔離性。所以ThreadLocal是一種編寫代碼的思路,但是并不是只能采用這種方式才行。最后抄個例子,簡單的說明下這個東東怎么用。
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; }
}
? ??