线程封闭

把对象封装到一个线程里,只有这一个线程能看到这个对象。所以即使这个对象不是线程安全的,也不会出现线程安全的问题了。
线程封闭 - threadLocal简单用法

创建类RequestHolder,

定义一个静态成员变量
ThreadLocal requestHolder = new ThreadLocal<>();
并定义三个方法,add(),getId(),remove(),分别表示想requestHolder 中添加对象,获取对象,移除对象

线程封闭 - threadLocal简单用法

定义Filter

线程封闭 - threadLocal简单用法

定义Interceptor

线程封闭 - threadLocal简单用法

将Filter和Interceptor 注入

线程封闭 - threadLocal简单用法

测试代码:

线程封闭 - threadLocal简单用法

执行结果:
线程封闭 - threadLocal简单用法

日志:
线程封闭 - threadLocal简单用法

代码git地址:
https://gitee.com/nannirongrong/concurrency.git

相关文章:

  • 2021-09-19
  • 2021-05-29
  • 2021-06-09
  • 2021-10-23
  • 2021-05-14
  • 2021-10-27
猜你喜欢
  • 2021-10-24
  • 2022-12-23
  • 2021-06-11
  • 2021-09-07
  • 2021-05-22
  • 2021-09-11
  • 2021-04-24
相关资源
相似解决方案