Java程序员从笨鸟到菜鸟(四十五) ThreadLocal 的理解

一、定义

ThreadLocal 提供一个线程(Thread)局部变量,使每一个线程都拥有自己的局部变量,ThreadLocal 就是在多线程的环境下取保证成员变量的安全

二、深入理解 ThreadLocal 类

常用方法:

public T get() {};
public void set(T value) {};
public void remove() {};
protected T initialValue() {};

get() 方法用来获取 ThreadLocal 在当前线程中保存的变量副本,set() 用来设置当前线程变量中的副本,remove() 用来移除线程中变量的副本,initialValue() 是一个 protected 方法,一般用来在使用时进行重写,是一个延迟加载方法

get() 方法:

/**
 * 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();
}

先获取当前线程,然后通过 getMap(t) 方法取到一个 map,然后再获取

 /**
   * 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;
  }

调用当前线程 t,返回当前线程 t 的一个成员变量 threadLocals,实际上就是一个 ThreadLocalMap

/* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

ThreadLocalMap实现:

/**
  * The entries in this hash map extend WeakReference, using
  * its main ref field as the key (which is always a
  * ThreadLocal object).  Note that null keys (i.e. entry.get()
  * == null) mean that the key is no longer referenced, so the
  * entry can be expunged from table.  Such entries are referred to
  * as "stale entries" in the code that follows.
  */
 static class Entry extends WeakReference<ThreadLocal<?>> {
     /** The value associated with this ThreadLocal. */
     Object value;

     Entry(ThreadLocal<?> k, Object v) {
         super(k);
         value = v;
     }
 }

ThreadLocalMap 的 Entry 继承了 WeakReference,并且使用 ThreadLocal 作为键值

setInitialValue()方法实现

/**
  * Variant of set() to establish initialValue. Used instead
  * of set() in case user has overridden the set() method.
  *
  * @return the initial value
  */
 private T setInitialValue() {
     T value = initialValue();
     Thread t = Thread.currentThread();
     ThreadLocalMap map = getMap(t);
     if (map != null)
         map.set(this, value);
     else
         createMap(t, value);
     return value;
 }

如果 map 不为空,就设置键值对,为空,再创建 Map

createMap() 实现

/**
  * 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);
 }

ThreadLocal 如何为每个线程创建变量的副本:
首先每个线程 Thread 内部都有一个 ThreadLocal.ThreadLocalMap 类型的成员变量 ThreadLocals,这个 threadLocals 就是存储实际的变量副本,键值为当前 ThreadLocal 变量,value 为变量副本(即 T 类型的变量)

初始时,在 Thread 里面,threadLocals 为空,并通过 ThreadLocal 变量调用 get() 方法或则 set() 方法,就会对 Thread 的 threadLocals 进行初始化,并且以当前 ThreadLocal 变量为键值,以 ThreadLocal 要保存的副本变量为 value,存到 threadLocals

总结:

  1. 在 get 之前,必须先 set ,否则会报空指针异常,如果在 get 之前不需要调用 set 就能正常访问的话,必须重写 initialValue()
  2. 通过 ThreadLocal 创建的副本是存储在每个线程自己的 threadLocals 中
  3. 为何 ThreadLocalMap 的键值为 ThreadLocal 对象,因为每个线程有多个 ThreadLocal 对象

三、ThreadLocal 的应用场景

最常见的使用场景是用来解决 数据库连接、session 管理等。

原文传送门:https://www.cnblogs.com/dolphin0520/p/3920407.html 非常感谢作者

深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值