ThreadLocal 介绍
本地线程,提供了线程的局部变量,针对每个线程,都会创建自己的变量副本。
ThreadLocal 使用
主要用于在多线程环境下,单个线程在运行过程中都可能用到一些值时,可以使用ThreadLocal,比如:

上述图片中,object 对象作为一个参数分别传入到 method1,method2,method3。此时可以使用ThreadLocal,将object放入到ThreadLocal中。
private static ThreadLocal<Object> threadLocalObject = new ThreadLocal<>();
然后提供getter,setter方法,可以在整个线程调用过程中使用。
ThreadLocal 内部实现

内部类似于Map的格式存储,Map<Thread,Map<ThreadLocal,Object>>.
首先通过当前线程获取到entry节点,然后通过threadLocal获取到Object。
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
// 首先获取到当前线程
Thread t = Thread.currentThread();
// 通过当前线程获取到ThreadLocaMap然后,如果map不为空,则将this(ThreadLocal)和value放入map中。
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
// 获取到当前线程
Thread t = Thread.currentThread();
// 通过当前线程获取到ThreadLocaMap
ThreadLocalMap map = getMap(t);
if (map != null) {
// 通过ThreadMap获取entry的,然后通过entry获取到当前值value
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
本文深入解析了ThreadLocal在多线程环境中的应用,介绍了其如何为每个线程提供独立的变量副本,避免了线程间的数据冲突。同时,详细阐述了ThreadLocal的内部实现机制,包括其如何通过类似Map的结构存储数据,以及set和get方法的工作原理。

2742

被折叠的 条评论
为什么被折叠?



