ThreadLocal是什么
定义:提供线程局部变量;一个线程局部变量在多个线程中,分别有独立的值(副本)
特点:简单(开箱即用)、快速(无额外开销)、安全(线程安全)
场景:多线程场景(资源持有、线程一致性、并发计算、线程安全等场景)
ThreadLocal基本API
- 构造函数 ThreadLocal<T>()
- 初始化 initialValue()
- 服务器 get/set
- 回收 remove
使用 Synchronized
1@RestController 2public class StartController { 3 4 static Integer c = 0; 5 6 synchronized void __add() throws InterruptedException { 7 Thread.sleep(100); 8 c++; 9 } 10 11 @RequestMapping("/stat") 12 public Integer stat() { 13 return c; 14 } 15 16 @RequestMapping("/add") 17 public Integer add() throws InterruptedException { 18 //Thread.sleep(100); 19 //c++; 20 __add(); 21 return 1; 22 } 23 24}
使用ThreadLocal
1@RestController 2public class StartController { 3 4 static ThreadLocal<Integer> c = new ThreadLocal<Integer>() { 5 @Override 6 protected Integer initialValue() { 7 return 0; 8 } 9 }; 10 11 void __add() throws InterruptedException { 12 Thread.sleep(100); 13 c.set(c.get() + 1); 14 } 15 16 @RequestMapping("/stat") 17 public Integer stat() { 18 return c.get(); 19 } 20 21 @RequestMapping("/add") 22 public Integer add() throws InterruptedException { 23 __add(); 24 return 1; 25 } 26 27}