ThreadLocal

ThreadLocal是什么

 

    ThreadLocal这个词如果直接翻译就是“本地线程”,可是如果真的按“本地线程”来理解,那就确实大错特错了,ThreadLocal它并不是一个Thread,它跟Thread确实有关系,是用来维护Thread的有关变量的,把它命名为ThreadLocalVariable可能更容易让人理解,在多线程中ThreadLocal为变量在每个线程中都创建了一个跟特定线程有关的变量的副本,这样就可以使每个线程在运行中只可以使用与自己线程有关的特定的副本变量,而不会影响其它线程的副本变量,保证了线程间变量的隔离性。

 

    对于线程来说,当多个线程都用到变量时,通过ThreadLocal使每个线程都有一个本地的独属于自己的变量,这也是类名中“Local”所要表达的意思。 

 

ThreadLocal例子

 

    ThreadLocal内部其实是一个map集合,key是各自的线程,value是我们要放入的对象。我们先通过一个ThreadLocal的简单demo先来理解一下ThreadLocal。

 

    先来看MyThreadScopeData实体类,是对对象类型的数据封装,让外界不可直接操作ThreadLocal变量,我们通过单例模式得到这个实体类,这样的话让这个类针对不同线程分别创建一个独立的实例对象,然后将这个实例对象作为变量放到ThreadLocal中。

[java]  view plain copy
  1. package com.tgb.threadlocal;  
  2.   
  3. /** 
  4.  * 与ThreadLocal有关的实体对象 
  5.  * @author kang 
  6.  * 
  7.  */  
  8. public class MyThreadScopeData {  
  9.       
  10.     //声明一个ThreacLoacl  
  11.     private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>();  
  12.       
  13.     //通过单例模式来获取对象实例  
  14.     private MyThreadScopeData(){}  
  15.     public static MyThreadScopeData getThreadInstance(){  
  16.         MyThreadScopeData instance=map.get();  
  17.         if (instance ==null) {  
  18.             instance = new MyThreadScopeData();  
  19.             map.set(instance);  
  20.         }  
  21.         return instance;  
  22.     }  
  23.       
  24.     private String name;  
  25.     private int age;  
  26.   
  27.     public static ThreadLocal<MyThreadScopeData> getMap() {  
  28.         return map;  
  29.     }  
  30.     public static void setMap(ThreadLocal<MyThreadScopeData> map) {  
  31.         MyThreadScopeData.map = map;  
  32.     }  
  33.     public String getName() {  
  34.         return name;  
  35.     }  
  36.     public void setName(String name) {  
  37.         this.name = name;  
  38.     }  
  39.     public int getAge() {  
  40.         return age;  
  41.     }  
  42.     public void setAge(int age) {  
  43.         this.age = age;  
  44.     }  
  45.       
  46.       
  47. }  


    接下来是客户端调用类,我们在客户端代码中通过制造了两个线程,在每个线程中都生成一个随机数,然后把这个随机数放入到两个不同的threadlocal对象中,然后将数据从threadlocal中取出,打印出线程名称和取出来的数据;除了client客户端还包含了两个内部类,是用来从threadlocal对象中取出线程名称和数据并打印的

[java]  view plain copy
  1. package com.tgb.threadlocal;  
  2.   
  3. import java.util.Random;  
  4.   
  5. /** 
  6.  * 测试类关于ThreadLocal 
  7.  * @author kang 
  8.  * 
  9.  */  
  10. public class ThreadLocalTest {  
  11.   
  12.     private static ThreadLocal<Integer> x = new ThreadLocal<Integer>();  
  13.   
  14.     public static void main(String[] args) {  
  15.         ThreadLocal<String> ss = new ThreadLocal<String>();  
  16.         //制造两个线程  
  17.         for (int i = 0; i < 2; i++) {  
  18.             new Thread(new Runnable() {  
  19.                 @Override  
  20.                 public void run() {  
  21.                     //生成一个随机数并打印  
  22.                     int data = new Random().nextInt();  
  23.                     System.out.println(Thread.currentThread().getName()   
  24.                             + " has put data :" + data);  
  25.                       
  26.                     //将随机数放入两个不同的ThreadLocal中  
  27.                     x.set(data);  
  28.                     MyThreadScopeData.getThreadInstance().setName("name" + data);  
  29.                     MyThreadScopeData.getThreadInstance().setAge(data);  
  30.                   
  31.                     //从ThreadLocal中取出数据并打印  
  32.                     new A().get();  
  33.                     new B().get();  
  34.                     System.out.println("#########################################");  
  35.                 }  
  36.             }).start();  
  37.   
  38.         }  
  39.     }  
  40.   
  41.     //内部类A,从两个ThreadLocal对象中取出数据,并打印  
  42.     static class A {  
  43.         public void get() {  
  44.             //从value为int类型的ThreadLocal中取出数据,并打印  
  45.             int data = x.get();  
  46.             System.out.println("A from " + Thread.currentThread().getName()  
  47.                     + " get int :" + data);  
  48.               
  49.             //从ThreadLocal实体对象中取出线程中放入的数据  
  50.             MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();  
  51.             System.out  
  52.                     .println("A from " + Thread.currentThread().getName()  
  53.                             + " 实体对象数据: " + myData.getName() + ","  
  54.                             + myData.getAge());  
  55.         }  
  56.     }  
  57.   
  58.     //内部类B,从两个ThreadLocal对象中取出数据,并打印  
  59.     static class B {  
  60.         public void get() {  
  61.             //从value为int类型的ThreadLocal中取出数据,并打印  
  62.             int data = x.get();  
  63.             System.out.println("B from " + Thread.currentThread().getName()  
  64.                     + " get int :" + data);  
  65.               
  66.             //从ThreadLocal实体对象中取出线程中放入的数据  
  67.             MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();  
  68.             System.out  
  69.                     .println("B from " + Thread.currentThread().getName()  
  70.                             + " 实体对象数据: " + myData.getName() + ","  
  71.                             + myData.getAge());  
  72.         }  
  73.     }  
  74. }  

    我们看一下执行的结果:


Thread-1 has putdata :-458782705

A from Thread-1 getint :-458782705

A from Thread-1实体对象数据: name-458782705,-458782705

B from Thread-1 getint :-458782705

B from Thread-1实体对象数据: name-458782705,-458782705

#########################################

Thread-0 has putdata :1881149941

A from Thread-0 getint :1881149941

A from Thread-0实体对象数据: name1881149941,1881149941

B from Thread-0 getint :1881149941

B from Thread-0实体对象数据: name1881149941,1881149941

#########################################

 

    通过执行结果我们可以看出,在两个线程的执行过程中生成的随机数是不一样的,通过将数据放入ThreadLocal中并取出打印,我们发现每个线程中的数据是一致保持一致的,这也就证明了,ThreadLocal在同一线程中实现了线程内的数据共享,不同线程间我们实现了数据的隔离性。

 

ThreadLocal源码

 

    我们现在来看下ThreadLocal背后的代码是怎样实现的。

 

    先来看下ThreadLocal的常用方法:

[java]  view plain copy
  1. public T get() { }  
  2. public void set(T value) { }  
  3. public void remove() { }  


    get()方法是用来获取ThreadLocal在当前线程中保存的变量副本,set()用来设置当前线程中变量的副本,remove()用来移除当前线程中变量的副本

 

    首先我们先来看下ThreadLocal类是如何为每个线程创建变量的副本的:

[java]  view plain copy
  1. /** 
  2.  * Returns the value in the current thread's copy of this 
  3.  * thread-local variable.  If the variable has no value for the 
  4.  * current thread, it is first initialized to the value returned 
  5.  * by an invocation of the {@link #initialValue} method. 
  6.  * 
  7.  * @return the current thread's value of this thread-local 
  8.  */  
  9. public T get() {  
  10.     Thread t = Thread.currentThread();  
  11.     ThreadLocalMap map = getMap(t);  
  12.     if (map != null) {  
  13.         ThreadLocalMap.Entry e = map.getEntry(this);  
  14.         if (e != null) {  
  15.             @SuppressWarnings("unchecked")  
  16.             T result = (T)e.value;  
  17.             return result;  
  18.         }  
  19.     }  
  20.     return setInitialValue();  
  21. }  


    首先通过currentThread()获取当前运行线程,然后通过getMap(t)方法获取到一个map,map的类型为ThreadLocalMap,如果map不为空就通过当前的ThreadLocal取出map中存取的value,如果为空就调用setInitialValue()方法创建ThreadLocalMap并经value进行返回。

 

    我们继续对上面的get()方法进行详细的分析,我们接下来看下getMap(t)方法,

[java]  view plain copy
  1. /** 
  2.  * Get the map associated with a ThreadLocal. Overridden in 
  3.  * InheritableThreadLocal. 
  4.  * 
  5.  * @param  t the current thread 
  6.  * @return the map 
  7.  */  
  8. ThreadLocalMap getMap(Thread t) {  
  9.     return t.threadLocals;  
  10. }  
 

    意思就是利用currentThread()获取当前运行线程t,然后得到t的成员变量threadLocalsthreadLocals又是什么,我们接着往下看,

[java]  view plain copy
  1. /* ThreadLocal values pertaining to this thread. This map is maintained 
  2.  * by the ThreadLocal class. */  
  3. ThreadLocal.ThreadLocalMap threadLocals = null;  
 

    threadLocals是ThreadLocal类的一个内部类ThreadLocalMap,我们接着看内部类ThreadLocalMap的实现,

[java]  view plain copy
  1. /** 
  2.    * ThreadLocalMap is a customized hash map suitable only for 
  3.    * maintaining thread local values. No operations are exported 
  4.    * outside of the ThreadLocal class. The class is package private to 
  5.    * allow declaration of fields in class Thread.  To help deal with 
  6.    * very large and long-lived usages, the hash table entries use 
  7.    * WeakReferences for keys. However, since reference queues are not 
  8.    * used, stale entries are guaranteed to be removed only when 
  9.    * the table starts running out of space. 
  10.    */  
  11.   static class ThreadLocalMap {  
  12.   
  13.       /** 
  14.        * The entries in this hash map extend WeakReference, using 
  15.        * its main ref field as the key (which is always a 
  16.        * ThreadLocal object).  Note that null keys (i.e. entry.get() 
  17.        * == null) mean that the key is no longer referenced, so the 
  18.        * entry can be expunged from table.  Such entries are referred to 
  19.        * as "stale entries" in the code that follows. 
  20.        */  
  21.       static class Entry extends WeakReference<ThreadLocal<?>> {  
  22.           /** The value associated with this ThreadLocal. */  
  23.           Object value;  
  24.   
  25.           Entry(ThreadLocal<?> k, Object v) {  
  26.               super(k);  
  27.               value = v;  
  28.           }  
  29.       }  


    可以看到ThreadLocalMap的内部类Entry继承了WeakReference,并且使用ThreadLocal作为键值,利用ThreadLocal的变量作为value,代码跟到这里我的目的就达到了,所以这里ThreadLocalMap本质就是利用Entry构造了一个keyvalue对,其实关于ThreadLocal的核心代码都在这个类中,感兴趣的同学可以自己接着往下看。

 

    我们get()方法里还有setInitialValue(),是当map为空时返回value用的,我们看下它的代码:

[java]  view plain copy
  1. /** 
  2.  * Variant of set() to establish initialValue. Used instead 
  3.  * of set() in case user has overridden the set() method. 
  4.  * 
  5.  * @return the initial value 
  6.  */  
  7. private T setInitialValue() {  
  8.     T value = initialValue();  
  9.     Thread t = Thread.currentThread();  
  10.     ThreadLocalMap map = getMap(t);  
  11.     if (map != null)  
  12.         map.set(this, value);  
  13.     else  
  14.         createMap(t, value);  
  15.     return value;  
  16. }  
 

    在这个方法里通过initialValue()获取value,获取当前线程,如果map不为空就对map进行赋值要注意key是当前的ThreadLocal,为空就进行创建map与直接赋值不一样key为当前Thread,同一个map为什么不一样,这里就卖个关子不再介绍了,大家在往下跟层代码看看就明白了。

 

    我们在看setInitialValue()中的方法initialValue()如何来获取value

 

[java]  view plain copy
  1. /** 
  2.  * An extension of ThreadLocal that obtains its initial value from 
  3.  * the specified {@code Supplier}. 
  4.  */  
  5. static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {  
  6.   
  7.     private final Supplier<? extends T> supplier;  
  8.   
  9.     SuppliedThreadLocal(Supplier<? extends T> supplier) {  
  10.         this.supplier = Objects.requireNonNull(supplier);  
  11.     }  
  12.   
  13.     @Override  
  14.     protected T initialValue() {  
  15.         return supplier.get();  
  16.     }  
  17. }  


    通过ThreadLocal的内部类SuppliedThreadLocalinitialValue()方法得到泛型,并进行返回。

 

    到这里我们就将get()方法如何为ThreadLocal的每个线程创建变量的副本的详细的介绍完了,跟踪完了以后发现确实挺简单,在每个线程Thread内部有一个ThreadLocal.ThreadLocalMap类型的成员变量threadLocals,这个threadLocals就是用来存储实际的变量副本的,键值为当前ThreadLocal变量,value为变量副本(即T类型的变量)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值