由Looper中的ThreadLocal谈起--论ThreadLocal的使用

        这两天在对Android的消息机制(handler)进行深入的了解和学习,在研究相应的源码的过程中,发现在Looper中被使用的ThreadLocal,对于它的作用出于好奇便进行了一些比较简单的分析,现在将我的学习心得公布如下:

        ThreadLocal这个类,相信对于之前从来都没有接触过这个类的程序猿来说,也许会把它认为是一个线程类。其实不然,它的作用可以大致理解为在各个线程中用来存储数据。需要举例来进行说明的话,那可以以Handler为例来进行说明:Handler需要获取当前线程中的Looper对象,但是不同的线程中含有不同的Looper对象,这个时候使用ThreadLocal对Looper进行保存,那就实现了在不同的线程中读取到的Looper对象就是相应的那个线程中的。

        ThreadLocal在android源码中的Looper、ActivityThread以及AMS中都有涉及。概括来说,ThreadLocal是一个线程内部的数据存储类,通过它就可以在指定的线程中存储数据,然后只有在这个指定的线程中才能够访问得到之前存储的数据。但是对于其他线程来说,是获取不到保存在另外线程中的数据的。一般来说,当某些数据是以线程为作用域并且不同的线程对应着不同的数据副本的时候,就可以考虑使用ThreadLocal了。下面通过一个代码示例来说明其作用。

[java]  view plain  copy
  1. public class ThreadLocalTestAct extends Activity {  
  2.   
  3.     private static final String TAG = "ThreadLocalTestAct";  
  4.   
  5.     private ThreadLocal<String> mThreadLocal = new ThreadLocal<String>();  
  6.   
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.activity_thread_local_test);  
  11.   
  12.         //main thread  
  13.         mThreadLocal.set("this is thread=======" + Thread.currentThread().getName());  
  14.         Log.d(TAG, "mThreadLocal 's value=======" + mThreadLocal.get());  
  15.   
  16.         new Thread("Thread#1") {  
  17.   
  18.             @Override  
  19.             public void run() {  
  20.                 super.run();  
  21.   
  22.                 mThreadLocal.set("this is thread=======" + Thread.currentThread().getName());  
  23.                 Log.d(TAG, "mThreadLocal 's value=======" + mThreadLocal.get());  
  24.             }  
  25.         }.start();  
  26.   
  27.         new Thread("Thread#2") {  
  28.   
  29.             @Override  
  30.             public void run() {  
  31.                 super.run();  
  32.                 Log.d(TAG, "mThreadLocal 's value=======" + mThreadLocal.get());  
  33.   
  34.             }  
  35.         }.start();  
  36.     }  
  37. }  

        代码比较简单,执行之后的结果如下:

        通过上述的小Demo,我想读者肯定是明白了ThreadLocal的作用了。而它之所以有这样的结果就是因为不同的线程访问同一个ThreadLocal的get方法,ThreadLocal会从各自线程中抽出一个数组,然后再从数组中根据当前的ThreadLocal的索引去查找出对应的value值。结果可知,不同的线程中的数组肯定是不同的,这也就是为什么通过ThreadLocal可以在不同的线程中维护一套数据而且还相互不干扰的原因了。

        如果从源码的角度上来简要分析的话,我们可以来简单的看一下ThreadLocal的源码,最主要的就是这个set方法和get方法了吧。

        set方法源码如下:

[java]  view plain  copy
  1. /** 
  2.      * Sets the value of this variable for the current thread. If set to 
  3.      * {@code null}, the value will be set to null and the underlying entry will 
  4.      * still be present. 
  5.      * 
  6.      * @param value the new value of the variable for the caller thread. 
  7.      */  
  8.     public void set(T value) {  
  9.         Thread currentThread = Thread.currentThread();  
  10.         Values values = values(currentThread);  
  11.         if (values == null) {  
  12.             values = initializeValues(currentThread);  
  13.         }  
  14.         values.put(this, value);  
  15.     }  
[java]  view plain  copy
  1. /** 
  2.         * Sets entry for given ThreadLocal to given value, creating an 
  3.         * entry if necessary. 
  4.         */  
  5.        void put(ThreadLocal<?> key, Object value) {  
  6.            cleanUp();  
  7.   
  8.            // Keep track of first tombstone. That's where we want to go back  
  9.            // and add an entry if necessary.  
  10.            int firstTombstone = -1;  
  11.   
  12.            for (int index = key.hash & mask;; index = next(index)) {  
  13.                Object k = table[index];  
  14.   
  15.                if (k == key.reference) {  
  16.                    // Replace existing entry.  
  17.                    table[index + 1] = value;  
  18.                    return;  
  19.                }  
  20.   
  21.                if (k == null) {  
  22.                    if (firstTombstone == -1) {  
  23.                        // Fill in null slot.  
  24.                        table[index] = key.reference;  
  25.                        table[index + 1] = value;  
  26.                        size++;  
  27.                        return;  
  28.                    }  
  29.   
  30.                    // Go back and replace first tombstone.  
  31.                    table[firstTombstone] = key.reference;  
  32.                    table[firstTombstone + 1] = value;  
  33.                    tombstones--;  
  34.                    size++;  
  35.                    return;  
  36.                }  
  37.   
  38.                // Remember first tombstone.  
  39.                if (firstTombstone == -1 && k == TOMBSTONE) {  
  40.                    firstTombstone = index;  
  41.                }  
  42.            }  
  43.        }  

       以上对于set方法来说,其源码中的Values类的作用是什么呢?其实在Thread类的内部有一个成员专门来存储线程的ThreadLocal类的数据,这样的话,获取当前线程中的ThreadLocal的数据就很简单了,如果values的值为空,那就实例化这个对象,之后再对相应的数据进行存储。第13行的table变量就是我们的说的存储数据的数组了,我们可以发现ThreadLocal的值在table数组中的存储位置总是被固定在ThreadLocal的reference字段所代表对象的后一位。这样我们就知道了其数据在内部被存储的过程了,对于get方法也比较好了解了。

        get方法如下:

[java]  view plain  copy
  1. /** 
  2.      * Returns the value of this variable for the current thread. If an entry 
  3.      * doesn't yet exist for this variable on this thread, this method will 
  4.      * create an entry, populating the value with the result of 
  5.      * {@link #initialValue()}. 
  6.      * 
  7.      * @return the current value of the variable for the calling thread. 
  8.      */  
  9.     @SuppressWarnings("unchecked")  
  10.     public T get() {  
  11.         // Optimized for the fast path.  
  12.         Thread currentThread = Thread.currentThread();  
  13.         Values values = values(currentThread);  
  14.         if (values != null) {  
  15.             Object[] table = values.table;  
  16.             int index = hash & values.mask;  
  17.             if (this.reference == table[index]) {  
  18.                 return (T) table[index + 1];  
  19.             }  
  20.         } else {  
  21.             values = initializeValues(currentThread);  
  22.         }  
  23.   
  24.         return (T) values.getAfterMiss(this);  
  25.     }  

        我们可以看到还是先得到当前thread的values对象,如果该对象为空的话,那就初始化,之后返回值即可(当然我们可以明显知道返回值是null);如果values值不空,那就将table数组中的reference字段之后的那个数据项返回,这也就印证了上面所说的ThreadLocal将存储的数据放在table数组中reference字段之后的结论。
        

转载:http://blog.csdn.net/u011619211/article/details/51388430

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值