• 系列二、为什么要使用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. }

  • 相关阅读:
    MATLAB神经网络和优化算法
    FireFox火狐浏览器电脑端安装到D盘
    java计算机毕业设计瀚绅睿茨二人二轮车租赁管理MyBatis+系统+LW文档+源码+调试部署
    MySQL尾部空格处理与哪些设置有关? 字符集PAD SPACE与NO PAD属性的区别、MySQL字段尾部有空格为什么也能查询出来?
    线程的生命周期以及其中的方法
    APP上架需要的准备和流程
    使用Python的Flask框架开发验证码登录功能
    开源 SPL 消灭数以万计的数据库中间表
    PHP分类信息网站源码系统 电脑+手机+微信端三合一 带完整前后端部署教程
    恭喜元宇宙产业委秘书长何超、执行秘书长武艳芳成为南京河西CBD发展大使
  • 原文地址:https://blog.csdn.net/HelloWorld20161112/article/details/134545106