ThreadLocal的使用

 1 /**
 2  * ThreadLocal<T>是Thread的一个属性,它是一个threadlocalmap类型。在一个线程刚开始执行的时候,通过ThreadLocal的set方法将值放在threadlocalmap中,在后面的类的方法中,可以获得map中的值
 3  * 常用的用法就是在一个web项目中,通过拦截器先获取请求用户的信息,将其放入SeissonStore(存放user的ThreadLocal),
 4  * 然后执行后面的业务代码时,不需要再将user对象作为参数传入
 5  * 直接调用get方法就能获取user
 6  * 
 7  * @Attention :因为threadlocal的set方法使将this(本身)放入threadlocalmap中作为key的,所以使用SessionStore的话只能使用单例模式,可以自己实现,或者用spring的方法,getBean,他是默认返回单列的
 8  * @author chenq
 9  * 2016-7-15 上午10:48:37
10  */
11 public class StringStoreTest {
12     public static void main(String[] args) {
13         StringStore.get().setString("chenq");
14         new AnotherClass().print();
15     }
16 }
 1 public class StringStore {
 2     
 3     private final ThreadLocal<String> store = new ThreadLocal<String>();
 4     
 5     public void setString(String str) {
 6         store.set(str);
 7     }
 8     public String getString() {
 9         return store.get();
10     }
11     
12     private StringStore() {};
13     
14     private static StringStore ss = null;
15     
16     public static StringStore get() {
17         if (ss == null) {
18             ss = new StringStore();
19         }
20         return ss;
21     }
22 }
1 public class AnotherClass {
2     
3     public void print() {
4         System.out.println(StringStore.get().getString());
5     }
6     
7 }

 

转载于:https://my.oschina.net/u/3724493/blog/1570350

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值