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

原文地址:https://www.cnblogs.com/ooo0/p/12877273.html