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 }

 

posted @ 2016-07-15 11:14  林暗草惊风丶  阅读(691)  评论(0编辑  收藏  举报