ThreadLocal实现线程范围的共享变量

来源:互联网 发布:辛辛那提大学轴承数据 编辑:程序博客网 时间:2024/05/22 23:40

这里先说下ThreadLocal不是一个线程的本地实现版本,不是一个Thread,它是thread local variable(线程局部变量);用于实现线程内的数据共享,即对于相同的程序代码,多个模块在同一个线程中运行时要共享一份数据,而在另外线程中运行时又共享另外一份数据。换一句话说就是为每一个使用该变量的线程都提供一个变量值的副本,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。从线程的角度看,就好像每一个线程都完全拥有该变量

现做一个小练习,定义一个全局共享的ThreadLocal变量,然后启动五个线程向该ThreadLocal变量中存储一个随机值,接着各个线程调用另外其他多个类的方法,这多个类的方法中读取这个ThreadLocal变量的值,就可以看到多个类在同一个线程中共享同一份数据。

 

定义两个类TestA TestB,用于获取值MyThreadLocal类中的X

TestA:

[html] view plaincopy
  1. package com.study.threadlocal;  
  2.   
  3. /**  
  4.  *   
  5.  * @ClassName: TestA  
  6.  * @Description: 用于获取 MyThreadLocal 中变量x的值  
  7.  * @author 我夕  
  8.   
  9.  */  
  10. public class TestA {  
  11.       
  12.     public void print(){  
  13.         System.out.println(Thread.currentThread()+": TestA ,x current value is:"+MyThreadLocal.getInstance().getX());  
  14.     }  
  15. }  



TestB:

[html] view plaincopy
  1. package com.study.threadlocal;  
  2. /**  
  3.  *   
  4.  * @ClassName: TestB  
  5.  * @Description: 用于获取 MyThreadLocal 中变量x的值  
  6.  * @author 我夕  
  7.  */  
  8. public class TestB {  
  9.     public void print(){  
  10.         System.out.println(Thread.currentThread()+": TestB ,x current value is:"+MyThreadLocal.getInstance().getX());  
  11.     }  
  12. }  



MyThreadLocal:

[html] view plaincopy
  1. package com.study.threadlocal;  
  2. /**  
  3.  *   
  4.  * @ClassName: MyThreadLocal  
  5.  * @Description: TODO  
  6.  * @author 我夕  
  7.  */  
  8. public class MyThreadLocal {  
  9.       
  10.     private Integer x;  
  11.       
  12.     //将构造器声明有私有的,避免外部创建他  
  13.     private MyThreadLocal(){}  
  14.       
  15.     private static ThreadLocal instanceThreadLocal=new ThreadLocal();//new ThreadLocal  
  16.       
  17.     public static MyThreadLocal getInstance(){  
  18.         MyThreadLocal instance=(MyThreadLocal)instanceThreadLocal.get();  
  19.         if(instance==null){  
  20.             instance=new MyThreadLocal();  
  21.             instanceThreadLocal.set(instance);  
  22.         }  
  23.         return instance;  
  24.     }  
  25.   
  26.     public Integer getX() {  
  27.         return x;  
  28.     }  
  29.   
  30.     public void setX(Integer x) {  
  31.         this.x = x;  
  32.     }  
  33.     //除去线程的方法  
  34.     public static void remove(){  
  35.         instanceThreadLocal.remove();  
  36.     }  
  37.   
  38. }  



ThreadLocalTest

[html] view plaincopy
  1. package com.study.threadlocal;  
  2.   
  3. import java.util.Random;  
  4.   
  5. /**  
  6.  *   
  7.  * @ClassName: ThreadLocalTest  
  8.  * @Description: 线程局部变量练习  
  9.  * @author 我夕  
  10.  */  
  11. public class ThreadLocalTest {  
  12.       
  13.     public static void main(String[] args) {  
  14.           
  15.         final TestA testA=new TestA();  
  16.         final TestB testB=new TestB();  
  17.           
  18.         //创建5个线程  
  19.         for(int i=0;i<5;i++){  
  20.             Thread thread=new Thread(new Runnable() {  
  21.                   
  22.                 @Override  
  23.                 public void run() {  
  24.                     //生成一个随机数字给x  
  25.                     MyThreadLocal.getInstance().setX(new Random().nextInt(100));  
  26.                     System.out.println(Thread.currentThread()+",X current value is:"+MyThreadLocal.getInstance().getX());  
  27.                     testA.print();  
  28.                     testB.print();  
  29.                     MyThreadLocal.getInstance().remove();  
  30.   
  31.                 }  
  32.             });  
  33.             thread.setName("thread_"+i);  
  34.             thread.start();  
  35.         }  
  36.           
  37.     }  
  38. }  


运行

从以上可以看出,TestA TestB确实在同一个线程中共享同一份数据。

 

接下来,分析下 ThreadLocal set()get()方法源码

set源码:

     /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to 
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }


 

get源码

[html] view plaincopy
  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.             return (T)e.value;  
  16.     }  
  17.     return setInitialValue();  
  18. }  

 

set()get()方法,我想大家应该都知道其的作用了,set设置当前线程的线程局部变量副本的值,get返回当前线程的线程局部变量副本的值,其set方法相当于往其内部的map中增加一条记录,key分别是各自的线程,value是各自的set方法传进去的值,在线程结束时可以调用ThreadLocal.clear()方法,这样会更快释放内存,不调用也可以,因为线程结束后也可以自动释放相关的ThreadLocal变量。

原创粉丝点击