ThreadLocal源码理解

TedVgu 7年前
   <h3><strong>缘起</strong></h3>    <p>平时开发、看源码经常会遇到ThreadLocal的使用,一直以来理解的不是那么清晰,只知道内部应该是某种类似map的实现,从而达到不同的线程调用get可以获取到不一样的值,仅此而已。趁着前一阵子中秋放假,正好有空,遂决定一探究竟,接下来我主要列下对源码的理解。</p>    <p>注意:本文研究的源码版本是Android6.0 sdk里的,实现有别于JDK中的版本。</p>    <h3><strong>1. 含义&用法</strong></h3>    <p>线程本地存储对象,同一个对象实例可以在多个Thread中操作,每个线程可以在这个对象上设置一个关联的值,各个线程看到的都是自己的值,互相之间不会影响;</p>    <p>在代码中一般作为静态字段使用,如Looper.java里面的:</p>    <pre>  <code class="language-java">// sThreadLocal.get() will return null unless you've called prepare().  static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();</code></pre>    <h3><strong>2. 初始值</strong></h3>    <p>可以通过覆写initialValue()方法提供个自定义的值;</p>    <h3><strong>3. set方法</strong></h3>    <p>代码如下:</p>    <pre>  <code class="language-java">public void set(T value) {          Thread currentThread = Thread.currentThread();          Values values = values(currentThread); // 拿到跟当前线程关联的values字段          if (values == null) {              values = initializeValues(currentThread);          }          values.put(this, value); // 将this、value对,放到这个结构中      }        /**       * Gets Values instance for this thread and variable type.       */      Values values(Thread current) {          return current.localValues;      }</code></pre>    <p>每个Thread对象有一个这里的Values类型的localValues字段。</p>    <h3><strong>4. Values结构:</strong></h3>    <p style="text-align:center"><img src="https://simg.open-open.com/show/e9a02882877a4343ccfb515921cd9189.png"></p>    <p style="text-align:center">Values结构</p>    <p>这里的重点是里面的 private Object[] table; 数组;</p>    <p>因为同一个线程可以创建多个ThreadLocal对象,所以这里用了一个数组来存储!!!数组中的存储方式是接连着存放,比如0,1位置是一对,分别对应key(ThreadLocal对象本身)、value,2和3位置是一对等等,数组长度一定是2的power(次方)。</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/c88024c3fc20</p>    <p> </p>