threadlocal
一個線程內部的存儲類,可以在指定線程內存儲數據,數據存儲以後,只有指定線程可以得到存儲數據。
static final ThreadLocal<T> threadLocal = new ThreadLocal<T>();
threadLocal.set("aa");
threadLocal.get();
他的實現原理大致可以這樣理解:
通過線程的名字,獲取對應的value值。
模擬實現原理,這裏不是說源碼實現
public class ThreadLocalSimulator<T> {
private final Map<Thread,T> storage = new HashMap<>();
public synchronized void set(T t){
synchronized (this){
Thread key = Thread.currentThread();
storage.put(key,t);
}
}
public synchronized T get(){
synchronized (this){
Thread key = Thread.currentThread();
T value = storage.get(key);
if(value == null){
return initValue();
}
return value;
}
}
private T initValue() {
return null;
}
}
在實際開發中,可能又很多方法需要傳參,用對象封裝的話,就是一傳到底
public class ActionContext {
private static final ThreadLocal<Context> th = new ThreadLocal<Context>(){
@Override
protected Context initialValue() {
return new Context();
}
};
private static class ContextHolder{
private static final ActionContext actionContext = new ActionContext();
}
public static ActionContext getInstance(){
return ContextHolder.actionContext;
}
public Context getContext(){
return th.get();
}
}
Context 作爲參數傳遞封裝的容器
上面的方法,通過getContext 方法獲取當前線程的需要傳遞的值,避免了一傳到底的現象