首页 > 系统相关 >【Java】ThreadLocal 可以在指定线程内存储数据,只有指定线程可以得到存储数据

【Java】ThreadLocal 可以在指定线程内存储数据,只有指定线程可以得到存储数据

时间:2022-12-13 10:32:47浏览次数:60  
标签:map 存储 thread ThreadLocalMap 指定 value ThreadLocal 线程


 

一般事务会用到 ThreadLocal 可以保障同一个线程用同一个 Connection

 

可以参考


 

ThreadLocal 是线程的内部存储类,可以在指定线程内存储数据。只有指定线程可以得到存储数据。

 

 

返回当前线程的这个副本的值
线程局部变量。如果变量没有值
当前线程,它首先被初始化为返回的值
通过调用{@link #initialValue}方法。

 @返回当前线程的线程本地值

/**
* 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();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}

 

获取与ThreadLocal关联的映射。覆盖在
 InheritableThreadLocal。

 @param t当前线程
 @返回地图

/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}

 

每个线程都有一个ThreadLocalMap的实例对象,并且通过ThreadLocal管理ThreadLocalMap。

/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}

 

 

 

 

 

 

 

 

标签:map,存储,thread,ThreadLocalMap,指定,value,ThreadLocal,线程
From: https://blog.51cto.com/u_14976802/5932946

相关文章