zoukankan      html  css  js  c++  java
  • java ThreadLocal

    ThreadLocal是什么

    定义:提供线程局部变量;一个线程局部变量在多个线程中,分别有独立的值(副本)

    特点:简单(开箱即用)、快速(无额外开销)、安全(线程安全)

    场景:多线程场景(资源持有、线程一致性、并发计算、线程安全等场景)

     

    ThreadLocal基本API 

    • 构造函数 ThreadLocal<T>()
    • 初始化 initialValue()
    • 服务器 get/set
    • 回收 remove

    使用 Synchronized

    @RestController
    public class StartController {
    
        static Integer c = 0;
    
        synchronized void  __add() throws InterruptedException {
            Thread.sleep(100);
            c++;
        }
    
        @RequestMapping("/stat")
        public Integer stat() {
            return c;
        }
    
        @RequestMapping("/add")
        public Integer add() throws InterruptedException {
            //Thread.sleep(100);
            //c++;
            __add();
            return 1;
        }
    
    }

    使用ThreadLocal

    @RestController
    public class StartController {
    
        static ThreadLocal<Integer> c = new ThreadLocal<Integer>() {
            @Override
            protected Integer initialValue() {
                return 0;
            }
        };
    
        void __add() throws InterruptedException {
            Thread.sleep(100);
            c.set(c.get() + 1);
        }
    
        @RequestMapping("/stat")
        public Integer stat() {
            return c.get();
        }
    
        @RequestMapping("/add")
        public Integer add() throws InterruptedException {
            __add();
            return 1;
        }
    
    }

    参考文章:https://www.yuque.com/gaohanghang/vx5cb2/wnvbvd#Fs5Am

  • 相关阅读:
    Spring 拦截器postHandle无法修改Response的原因
    使用AShot进行网页全页截图
    60句简短的话 句句在理
    天使
    路过青春的合欢树
    Velocity日期格式化
    高斯模糊的Java实现
    MyBatis架构与源码分析<资料收集>
    柳青(Jean)英文演讲集合
    hive sql 常见异常
  • 原文地址:https://www.cnblogs.com/ooo0/p/12877273.html
Copyright © 2011-2022 走看看