ThreadLocal及应用

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 方法获取当前线程的需要传递的值,避免了一传到底的现象

发布了68 篇原创文章 · 获赞 6 · 访问量 6670

猜你喜欢

转载自blog.csdn.net/renguiriyue/article/details/104715854