You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23 lines
1.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### Threadlocal
- 多线程并发场景,在同线程的不同组件传递公共变量
- 每个线程变量都是独立隔离的
### 常用方法
- set设置当前线程绑定局部变量
- get获取当前线程绑定局部变量
- remove 移除当前线程绑定局部变量
### 与synchronization 区别
- 可以对变量进行加锁轻量级
- synchronization以时间换空间、排队取资源
- thread local以空间换时间提供变量副本数据隔离
### thredlocal优点
- 1.传递数据︰保存每个线程绑定的数据,在需要的地方可以直接获取,避免参数直接传递带来的代码耦合问题
- 2.线程隔离︰各线程之间的数据相互隔离却又具备并发性,避免同步方式带来的性能损失
### threadlocal内部
- ![img_5.png](img_5.png)
- 在thread内部有一个threadlocalmap存储threadlocal对象和线程变量副本作为key
### Threadlocal应用场景
- 在重入方法中代替传参
- Threadlocal代替Session使用全局存储用户信息