ThreadLocal工具类的使用(隔离思想)

ThreadLocal不是用来解决共享对象的多线程访问问题的

            通过ThreadLocal的set()方法设置到线程的ThreadLocal.ThreadLocalMap里的是是线程自己要存储的对象,其他线程不需要去访问,也是访问不到的。各个线程中的ThreadLocal.ThreadLocalMap以及ThreadLocal.ThreadLocal中的值都是不同的对象。

set仅仅是表示将线程ThreadLoaclMap中table处的value值重新设置,即覆盖。

对于同一个ThreadLocal对象而言,set后,table中绝不会多出一个数据:

1
2
3
4
public  class  Tools
{
     public  static  ThreadLocal<String> t1 =  new  ThreadLocal<String>();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public  class  ThreadLocalThread  extends  Thread
{
     private  static  AtomicInteger ai =  new  AtomicInteger();
 
     public  ThreadLocalThread(String name)
     {
         super (name);
     }
 
     public  void  run()
     {
         try
         {
             for  ( int  i =  0 ; i <  3 ; i++)
             {
                 Tools.t1.set(ai.addAndGet( 1 ) +  "" );
                 System.out.println( this .getName() +  " get value--->"  + Tools.t1.get());
                 Thread.sleep( 200 );
             }
         }
         catch  (InterruptedException e)
         {
             e.printStackTrace();
         }
     }
}
<wiz_tmp_tag class="wiz-block-scroll">
 

1、ThreadLocal不是集合,它不存储任何内容,真正存储数据的集合在Thread中。ThreadLocal只是一个工具,一个往各个线程的ThreadLocal.ThreadLocalMap中table的某一位置set一个值的工具而已2、同步与ThreadLocal是解决多线程中数据访问问题的两种思路,前者是数据共享的思路,后者是数据隔离的思路

3、同步是一种以时间换空间的思想,ThreadLocal是一种空间换时间的思想

4、ThreadLocal和request区别:

(1)ThreadLocal只能存一个值,一个Request由于是Map形式的,可以用key-value形式存多个值

(2)ThreadLocal一般用在框架,Request一般用在表示层、Action、Servlet

 

猜你喜欢

转载自www.cnblogs.com/shuchen007/p/9202739.html