• ThreadLocal(1):ThreadLocal介绍


    1 官方介绍

    1. /**
    2. * This class provides thread-local variables. These variables differ from
    3. * their normal counterparts in that each thread that accesses one (via its
    4. * {@code get} or {@code set} method) has its own, independently initialized
    5. * copy of the variable. {@code ThreadLocal} instances are typically private
    6. * static fields in classes that wish to associate state with a thread (e.g.,
    7. * a user ID or Transaction ID).
    8. *
    9. *

      For example, the class below generates unique identifiers local to each

    10. * thread.
    11. * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
    12. * and remains unchanged on subsequent calls.
    13. *
    14. * import java.util.concurrent.atomic.AtomicInteger;
    15. *
    16. * public class ThreadId {
    17. * // Atomic integer containing the next thread ID to be assigned
    18. * private static final AtomicInteger nextId = new AtomicInteger(0);
    19. *
    20. * // Thread local variable containing each thread's ID
    21. * private static final ThreadLocal<Integer> threadId =
    22. * new ThreadLocal<Integer>() {
    23. * @Override protected Integer initialValue() {
    24. * return nextId.getAndIncrement();
    25. * }
    26. * };
    27. *
    28. * // Returns the current thread's unique ID, assigning it if necessary
    29. * public static int get() {
    30. * return threadId.get();
    31. * }
    32. * }
    33. *
  • *

    Each thread holds an implicit reference to its copy of a thread-local

  • * variable as long as the thread is alive and the {@code ThreadLocal}
  • * instance is accessible; after a thread goes away, all of its copies of
  • * thread-local instances are subject to garbage collection (unless other
  • * references to these copies exist).
  • *
  • * @author Josh Bloch and Doug Lea
  • * @since 1.2
  • */
  • public class ThreadLocal<T> {
  • ...
  • 从Java官方文档中的描述:ThreadLocal类用来提供线程内部的局部变量。这种变量在多线程环境下访问(通过get和set方法访问)时能保证各个线程的变量相对独立于其他线程内的变量。ThreadLocal实例通常来说都是private static类型的,用于关联线程和线程上下文。

    我们可以得知 ThreadLocal 的作用是:提供线程内的局部变量,不同的线程之间不会相互干扰,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或组件之间一些公共变量传递的复杂度。

    总结:

    1. 线程并发: 在多线程并发的场景下
    2. 传递数据: 我们可以通过ThreadLocal在同一线程,不同组件中传递公共变量
    3. 线程隔离: 每个线程的变量都是独立的,不会互相影响

    2 基本使用

    2.1 常用方法

    ​ 在使用之前,我们先来认识几个ThreadLocal的常用方法

    方法声明描述
    ThreadLocal()创建ThreadLocal对象
    public void set( T value)设置当前线程绑定的局部变量
    public T get()获取当前线程绑定的局部变量
    public void remove()移除当前线程绑定的局部变量

    2.2 使用案例

    我们来看下面这个案例 , 感受一下ThreadLocal 线程隔离的特点:

    1. /*
    2. * 需求: 线程隔离
    3. * 在多线程并发的场景下, 每个线程中的变量都是相互独立
    4. * 线程A : 设置(变量1 ) 获取(变量1
    5. * 线程B : 设置(变量2 ) 获取(变量2
    6. *
    7. * */
    8. public class MyDemo01 {
    9. //变量
    10. private String content;
    11. private String getContent() {
    12. return content;
    13. }
    14. private void setContent(String content) {
    15. this.content = content;
    16. }
    17. public static void main(String[] args) {
    18. MyDemo01 demo = new MyDemo01();
    19. for (int i = 0; i < 20; i++) {
    20. Thread thread = new Thread(new Runnable() {
    21. @Override
    22. public void run() {
    23. /*
    24. 每个线程: 存一个变量 , 过一会 取出这个变量
    25. */
    26. demo.setContent(Thread.currentThread().getName() + "的数据");
    27. System.out.println("-----------------------");
    28. System.out.println(Thread.currentThread().getName() + "--->" + demo.getContent());
    29. }
    30. });
    31. thread.setName("线程" + i); //线程0~4
    32. thread.start();
    33. }
    34. }
    35. }

    打印结果如下:

    1. -----------------------
    2. -----------------------
    3. 线程3--->线程3的数据
    4. -----------------------
    5. -----------------------
    6. 线程1--->线程3的数据
    7. 线程2--->线程3的数据
    8. 线程0--->线程3的数据
    9. -----------------------
    10. 线程4--->线程4的数据
    11. -----------------------
    12. 线程6--->线程6的数据
    13. -----------------------
    14. -----------------------
    15. 线程7--->线程7的数据
    16. 线程5--->线程7的数据
    17. -----------------------
    18. 线程8--->线程8的数据
    19. -----------------------
    20. 线程9--->线程9的数据
    21. -----------------------
    22. 线程17--->线程17的数据
    23. -----------------------
    24. 线程12--->线程12的数据
    25. -----------------------
    26. 线程13--->线程13的数据
    27. -----------------------
    28. 线程18--->线程18的数据
    29. -----------------------
    30. 线程19--->线程19的数据
    31. -----------------------
    32. 线程15--->线程19的数据
    33. -----------------------
    34. 线程11--->线程11的数据
    35. -----------------------
    36. 线程10--->线程10的数据
    37. -----------------------
    38. 线程16--->线程16的数据
    39. -----------------------
    40. 线程14--->线程14的数据
    41. Process finished with exit code 0

    从结果可以看出多个线程在访问同一个变量的时候出现的异常,线程间的数据没有隔离。下面我们来看下采用 ThreadLocal 的方式来解决这个问题的例子

    1. /*
    2. * 需求: 线程隔离
    3. * 在多线程并发的场景下, 每个线程中的变量都是相互独立
    4. * 线程A : 设置(变量1 ) 获取(变量1
    5. * 线程B : 设置(变量2 ) 获取(变量2
    6. *
    7. * ThreadLocal :
    8. * 1. set() : 将变量绑定到当前线程中
    9. * 2. get() : 获取当前线程绑定的变量
    10. * */
    11. public class MyDemo01 {
    12. ThreadLocal<String> tl = new ThreadLocal<>();
    13. //变量
    14. private String content;
    15. private String getContent() {
    16. return tl.get();
    17. }
    18. private void setContent(String content) {
    19. //变量content绑定到当前线程
    20. tl.set(content);
    21. }
    22. public static void main(String[] args) {
    23. MyDemo01 demo = new MyDemo01();
    24. for (int i = 0; i < 20; i++) {
    25. Thread thread = new Thread(new Runnable() {
    26. @Override
    27. public void run() {
    28. /*
    29. 每个线程: 存一个变量 , 过一会 取出这个变量
    30. */
    31. demo.setContent(Thread.currentThread().getName() + "的数据");
    32. System.out.println("-----------------------");
    33. System.out.println(Thread.currentThread().getName() + "--->" + demo.getContent());
    34. }
    35. });
    36. thread.setName("线程" + i); //线程0~4
    37. thread.start();
    38. }
    39. }
    40. }

    打印结果如下:

    1. -----------------------
    2. -----------------------
    3. 线程2--->线程2的数据
    4. 线程0--->线程0的数据
    5. -----------------------
    6. 线程1--->线程1的数据
    7. -----------------------
    8. -----------------------
    9. 线程3--->线程3的数据
    10. 线程4--->线程4的数据
    11. -----------------------
    12. -----------------------
    13. -----------------------
    14. 线程14--->线程14的数据
    15. 线程5--->线程5的数据
    16. -----------------------
    17. 线程8--->线程8的数据
    18. -----------------------
    19. 线程10--->线程10的数据
    20. -----------------------
    21. 线程11--->线程11的数据
    22. -----------------------
    23. -----------------------
    24. -----------------------
    25. 线程9--->线程9的数据
    26. -----------------------
    27. 线程16--->线程16的数据
    28. 线程6--->线程6的数据
    29. -----------------------
    30. 线程17--->线程17的数据
    31. 线程7--->线程7的数据
    32. -----------------------
    33. -----------------------
    34. 线程13--->线程13的数据
    35. -----------------------
    36. 线程12--->线程12的数据
    37. 线程15--->线程15的数据
    38. 线程19--->线程19的数据
    39. -----------------------
    40. 线程18--->线程18的数据
    41. Process finished with exit code 0

    从结果来看,这样很好的解决了多线程之间数据隔离的问题,十分方便。

    3 ThreadLocal类与synchronized关键字

    3.1 synchronized同步方式

    ​ 这里可能有的朋友会觉得在上述例子中我们完全可以通过加锁来实现这个功能。我们首先来看一下用synchronized代码块实现的效果:

    1. /*
    2. * 需求: 线程隔离
    3. * 在多线程并发的场景下, 每个线程中的变量都是相互独立
    4. * 线程A : 设置(变量1 ) 获取(变量1
    5. * 线程B : 设置(变量2 ) 获取(变量2
    6. *
    7. * */
    8. public class MyDemo02 {
    9. //变量
    10. private String content;
    11. private String getContent() {
    12. return content;
    13. }
    14. private void setContent(String content) {
    15. this.content = content;
    16. }
    17. public static void main(String[] args) {
    18. MyDemo02 demo = new MyDemo02();
    19. for (int i = 0; i < 20; i++) {
    20. Thread thread = new Thread(new Runnable() {
    21. @Override
    22. public void run() {
    23. /*
    24. 每个线程: 存一个变量 , 过一会 取出这个变量
    25. */
    26. synchronized (MyDemo02.class){
    27. demo.setContent(Thread.currentThread().getName() + "的数据");
    28. System.out.println("-----------------------");
    29. System.out.println(Thread.currentThread().getName() + "--->" + demo.getContent());
    30. }
    31. }
    32. });
    33. thread.setName("线程" + i); //线程0~4
    34. thread.start();
    35. }
    36. }
    37. }

    打印结果:

    1. -----------------------
    2. 线程0--->线程0的数据
    3. -----------------------
    4. 线程4--->线程4的数据
    5. -----------------------
    6. 线程7--->线程7的数据
    7. -----------------------
    8. 线程3--->线程3的数据
    9. -----------------------
    10. 线程2--->线程2的数据
    11. -----------------------
    12. 线程11--->线程11的数据
    13. -----------------------
    14. 线程1--->线程1的数据
    15. -----------------------
    16. 线程8--->线程8的数据
    17. -----------------------
    18. 线程9--->线程9的数据
    19. -----------------------
    20. 线程10--->线程10的数据
    21. -----------------------
    22. 线程6--->线程6的数据
    23. -----------------------
    24. 线程5--->线程5的数据
    25. -----------------------
    26. 线程18--->线程18的数据
    27. -----------------------
    28. 线程17--->线程17的数据
    29. -----------------------
    30. 线程13--->线程13的数据
    31. -----------------------
    32. 线程14--->线程14的数据
    33. -----------------------
    34. 线程16--->线程16的数据
    35. -----------------------
    36. 线程15--->线程15的数据
    37. -----------------------
    38. 线程12--->线程12的数据
    39. -----------------------
    40. 线程19--->线程19的数据
    41. Process finished with exit code 0

    ​ 从结果可以发现, 加锁确实可以解决这个问题,但是在这里我们强调的是线程数据隔离的问题,并不是多线程共享数据的问题, 在这个案例中使用synchronized关键字是不合适的。

    3.2 ThreadLocal与synchronized的区别

    ​虽然ThreadLocal模式与synchronized关键字都用于处理多线程并发访问变量的问题, 不过两者处理问题的角度和思路不同。

    synchronizedThreadLocal
    原理同步机制采用'以时间换空间'的方式, 只提供了一份变量,让不同的线程排队访问ThreadLocal采用'以空间换时间'的方式, 为每一个线程都提供了一份变量的副本,从而实现同时访问而相不干扰
    侧重点多个线程之间访问资源的同步多线程中让每个线程之间的数据相互隔离

    总结:在刚刚的案例中,虽然使用ThreadLocal和synchronized都能解决问题,但是使用ThreadLocal更为合适,因为这样可以使程序拥有更高的并发性。

  • 相关阅读:
    人脸识别5.1.1- insightface人脸检测模型blazeface_paddle
    Matlab数值计算与符号计算3-新版
    手机运行内存大揭秘:探索你手机的超级大脑!
    读书笔记之C Primer Plus 4
    518. 零钱兑换II(完全背包问题)
    深入理解JVM虚拟机第十八篇:JVM种局部变量表结构的认识
    对某钓鱼样本分析
    蜂鸟E203学习笔记(二)--蜂鸟E203总体框架
    MVP 聚技站|.NET C# 系列(二):创建并运行简单的 C# 控制台应用程序
    三显智能氮气柜温度、湿度和氧含量控制介绍
  • 原文地址:https://blog.csdn.net/u013938578/article/details/132853185