• 系列二、为什么要使用ThreadLocal?


    一、为什么要使用ThreadLocal?

    1.1、概述

            并发场景下,会存在多个线程同时修改一个共享变量的场景,这就有可能会出现线程安全的问题。为了解决线程安全问题,可以用加锁的方式,比如对核心代码使用synchronized或者Lock进行加锁,从而起到线程隔离的效果。但是加锁的方式,在高并发下会导致系统变慢,加锁示意图如下:

            还有另外一种方案,就是使用空间换时间的方式,即:使用ThreadLocal,使用ThreadLocal访问共享变量时,会在每个线程本地保存一份共享变量的副本。多线程对共享变量修改时,实际上每个线程操作的是自己的变量副本,从而保证线程安全。示意图如下:

    1.2、线程不安全案例

    1. /**
    2. * @Author : 一叶浮萍归大海
    3. * @Date: 2023/11/21 11:50
    4. * @Description: 需求:线程隔离(线程不安全案例代码)
    5. */
    6. public class SetAndGetThreadVariableDemo1MainApp {
    7. /**
    8. * 共享变量
    9. */
    10. private String content;
    11. public String getContent() {
    12. return content;
    13. }
    14. public void setContent(String content) {
    15. this.content = content;
    16. }
    17. public static void main(String[] args) {
    18. SetAndGetThreadVariableDemo1MainApp app = new SetAndGetThreadVariableDemo1MainApp();
    19. for (int i = 1; i <= 5; i++) {
    20. new Thread(() -> {
    21. try {
    22. app.setContent(Thread.currentThread().getName() + "的数据");
    23. System.out.println("=======================");
    24. System.out.println(Thread.currentThread().getName() + "===>" + app.getContent());
    25. } catch (Exception e) {
    26. e.printStackTrace();
    27. }
    28. }, "线程" + i).start();
    29. }
    30. }
    31. }

    1.3、线程不安全案例(ThreadLocal解决)

    1. /**
    2. * @Author : 一叶浮萍归大海
    3. * @Date: 2023/11/21 11:50
    4. * @Description: 需求:线程隔离(ThreadLocal实现)
    5. * 在多线程并发的场景下,每个线程中的变量都是互相独立的
    6. * 线程A: 设置(变量1) 获取(变量1)
    7. * 线程B: 设置(变量2) 获取(变量2)
    8. *
    9. * ThreadLocal:
    10. * 1、set():将变量绑定到当前线程中
    11. * 2、get():获取当前线程绑定的变量
    12. */
    13. public class SetAndGetThreadVariableDemo2MainApp {
    14. private String content;
    15. ThreadLocal threadLocal = new ThreadLocal<>();
    16. public String getContent() {
    17. return threadLocal.get();
    18. }
    19. public void setContent(String content) {
    20. threadLocal.set(content);
    21. }
    22. public static void main(String[] args) {
    23. SetAndGetThreadVariableDemo2MainApp app = new SetAndGetThreadVariableDemo2MainApp();
    24. for (int i = 1; i <= 5; i++) {
    25. new Thread(() -> {
    26. try {
    27. app.setContent(Thread.currentThread().getName() + "的数据");
    28. System.out.println("=======================");
    29. System.out.println(Thread.currentThread().getName() + "===>" + app.getContent());
    30. } catch (Exception e) {
    31. e.printStackTrace();
    32. }
    33. }, "线程" + i).start();
    34. }
    35. }
    36. }

    1.4、线程不安全案例(synchronized解决)

    1. /**
    2. * @Author : 一叶浮萍归大海
    3. * @Date: 2023/11/21 11:50
    4. * @Description: 需求:线程隔离(synchronized实现)
    5. *
    6. */
    7. public class SetAndGetThreadVariableDemo3MainApp {
    8. private String content;
    9. public String getContent() {
    10. return content;
    11. }
    12. public void setContent(String content) {
    13. this.content = content;
    14. }
    15. public static void main(String[] args) {
    16. SetAndGetThreadVariableDemo3MainApp app = new SetAndGetThreadVariableDemo3MainApp();
    17. for (int i = 1; i <= 5; i++) {
    18. new Thread(() -> {
    19. try {
    20. synchronized (SetAndGetThreadVariableDemo3MainApp.class) {
    21. app.setContent(Thread.currentThread().getName() + "的数据");
    22. System.out.println("=======================");
    23. System.out.println(Thread.currentThread().getName() + "===>" + app.getContent());
    24. }
    25. } catch (Exception e) {
    26. e.printStackTrace();
    27. }
    28. }, "线程" + i).start();
    29. }
    30. }
    31. }

  • 相关阅读:
    第7章 课程总结
    VueCLI脚手架
    算法岗常问的一些Python基础知识
    【无标题】
    一起来学Kotlin:概念:18. Kotlin open 关键字与类名、函数名和变量名的使用
    C++-RTTI-运行时类型识别-typeid类型名-dynamic_cast-多继承类型转换-详细分析-Com基础
    [JS] 网络请求相关
    2024年GPLT团体程序设计比赛L2-D吉利矩阵题解
    医院项目-预约挂号-第三部分
    IntelliJ IDEA 2023.2正式发布,新UI和Profiler转正
  • 原文地址:https://blog.csdn.net/HelloWorld20161112/article/details/134545106