Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 詳解 ThreadLocal 及 InheritableThreadLocal

編輯:關於 Android 程式設計

概要:

Android 中經常用 Handler 處理異步任務、操作 UI 線程,而 Looper 對象正是保存在 ThreadLocal 中的,因此有必要研究一下 ThreadLocal 的源碼。以下分析基於 Android SDK 23 源碼(Android 與 JDK 中的實現可能不同)。

初用 ThreadLocal 時,很容易誤以為它就是一個線程。先看個簡單例子。

一個簡單的 Person 類:

 public class Person {
 public String name;
 public int age;
 public Person(String name, int age) {
 this.name = name;
 this.age = age;
 }
 } 

一個簡單的 Activity:

 public class MainActivity extends Activity {
 //ThreadLocal 初始化
 private ThreadLocal<Person> mThreadLocal = new ThreadLocal<Person>();
 private Person mPerson = new Person("王大俠", 100);
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 //將 mPerson 對象設置進去
 mThreadLocal.set(mPerson);
 Log.d("主線程", " 名字:" + mThreadLocal.get().name + " 年齡:" + mThreadLocal.get().age);
 }
 } 

運行結果:

04-19 13:14:31.053 d/主線程: 名字:王大俠 年齡:100

果然拿到了,說明當前線程確實存儲了 mPerson 的引用。那開個子線程還能拿到嗎?

 public class MainActivity extends Activity {
 private ThreadLocal<Person> mThreadLocal = new ThreadLocal<Person>();
 private Person mPerson = new Person("王大俠", 100);
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 mThreadLocal.set(mPerson);
 new Thread(new Runnable() {
 @Override
 public void run() {
 Log.d("子線程", " 名字:" + mThreadLocal.get().name + " 年齡:" + mThreadLocal.get().age);
 }
 }).start();
 }
 } 

結果直接拋出空指針:

java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.example.franky.myapplication.Person.name' on a null object reference

子線程確實拿不到 mPerson。明明在主線程 set 過,為何子線程 get 不到?我們來追源碼。

ThreadLocal 的構造方法平淡無奇:

 public ThreadLocal() {}

再看類說明:

 implements a thread-local storage, that is, a variable for which each thread
 has its own value. all threads share the same ThreadLocal object, but each
 sees a different value when accessing it, and changes made by one thread do
 not affect the other threads.

大意是:每個線程都能在自己身上保持一份對象,一個線程改變它不會影響其他線程。但別誤讀——若某對象是共享變量,某線程改了它,其他線程訪問時自然也變了,所以 ThreadLocal 並不等於線程安全,只需理解它能在當前線程保存一個對象,省得他到處傳遞即可。

那它是線程嗎?看它是否繼承 Thread 就知道:

 public class ThreadLocal<T> { }

並沒有——所以 ThreadLocal 不是線程。接著看它是如何保存對象的,先看 set():

 public void set(T value) {
 Thread currentThread = Thread.currentThread();
 Values values = values(currentThread);
 if (values == null) {
 values = initializeValues(currentThread);
 }
 values.put(this, value);
 }

先拿到當前線程,傳給 values():

 Values values(Thread current) {
 return current.localValues;
 }

返回的是 Thread 類的成員變量:

ThreadLocal.Values localValues;

其類型正是 ThreadLocal 的內部類 Values。由於是初次設置,localValues 為 null,於是走 initializeValues:

 Values initializeValues(Thread current) {
 return current.localValues = new Values();
 }

直接 new 了一個 Values。看看它裡面有啥:

 Values() {
 initializeTable(INITIAL_SIZE);
 this.size = 0;
 this.tombstones = 0;
 }

INITIAL_SIZE 為 16,initializeTable 做了什麼?

 private void initializeTable(int capacity) {
 this.table = new Object[capacity * 2];
 this.mask = table.length - 1;
 this.clean = 0;
 this.maximumLoad = capacity * 2 / 3;
 }

初始化了長度 32 的 table 數組、mask 為 31、maximumLoad 為 10。table 是 Object[],可存放任何對象:

 /**
 * Map entries. Contains alternating keys (ThreadLocal) and values.
 * The length is always a power of 2.
 */
 private Object[] table;

原來保存的對象就放在這裡。其他變量:mask 用來計算下標,size 是存活對象數量,tombstones 是過時對象數量,maximumLoad 是最大保存量,clean 指向下一個要清理的位置。

回到 put:

 void put(ThreadLocal<?> key, Object value) {
 cleanUp();
 int firstTombstone = -1;
 for (int index = key.hash & mask;; index = next(index)) {
 Object k = table[index];
 if (k == key.reference) {
 table[index + 1] = value;
 return;
 }
 if (k == null) {
 if (firstTombstone == -1) {
 table[index] = key.reference;
 table[index + 1] = value;
 size++;
 return;
 }
 table[firstTombstone] = key.reference;
 table[firstTombstone + 1] = value;
 tombstones--;
 size++;
 return;
 }
 if (firstTombstone == -1 && k == TOMBSTONE) {
 firstTombstone = index;
 }
 }
 }

cleanUp() 負責清理過時對象、檢查是否超載或擴容。然後用 key.hash & mask 計算下標,key.hash 的初始值:

 private static AtomicInteger hashCounter = new AtomicInteger(0);
 private final int hash = hashCounter.getAndAdd(0x61c88647 * 2);

最關鍵的是:

 table[index] = key.reference;
 table[index + 1] = value;

這裡把自身的引用(而且是弱引用)放在 table[index],把 value 放在下一個位置,保證 key 和 value 排列在一起。可見 key 其實是 ThreadLocal 的引用,value 是真正的值,兩者一同放在 table 數組裡。

所以現在的情況是:Thread 的成員變量 localValues 是 ThreadLocal.Values 類型,也就是說當前線程持有了這個數據結構,我們 set 的 value 全存在裡面。若在一個線程裡 new 了很多 ThreadLocal,指向的都是同一個 localValues,只是分放在 table 的不同位置。

再看 get():

 public T get() {
 Thread currentThread = Thread.currentThread();
 Values values = values(currentThread);
 if (values != null) {
 Object[] table = values.table;
 int index = hash & values.mask;
 if (this.reference == table[index]) {
 return (T) table[index + 1];
 }
 } else {
 values = initializeValues(currentThread);
 }
 return (T) values.getAfterMiss(this);
 }

先拿當前線程及其 Values,再拿 table、算下標、取對象;取不到就走 getAfterMiss 返回 null。看它的實現:

 Object value = key.initialValue();
 protected T initialValue() {
 return null;
 }

我們可以覆寫 initialValue() 自定義返回值,有興趣可試試。

回到最初的疑問:為何子線程拿不到 mPerson?因為子線程的 localValues 裡並沒保存它,真正保存的是主線程,自然取不到。

看完 ThreadLocal,再看它的子類 InheritableThreadLocal。它最大的不同是能在子線程獲取到保存的對象:

 public class MainActivity extends Activity {
 private InheritableThreadLocal<Person> mInheritableThreadLocal = new InheritableThreadLocal<Person>();
 private Person mPerson = new Person("王大俠", 100);
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 mInheritableThreadLocal.set(mPerson);
 Log.d("主線程"+Thread.currentThread().getName(), " 名字:" + mInheritableThreadLocal.get().name + " 年齡:" + mInheritableThreadLocal.get().age);
 new Thread(new Runnable() {
 @Override
 public void run() {
 Log.d("子線程"+Thread.currentThread().getName(), " 名字:" + mInheritableThreadLocal.get().name + " 年齡:" + mInheritableThreadLocal.get().age);
 }
 }).start();
 }
 }

輸出:

D/主線程main: 名字:王大俠 年齡:100

D/子線程Thread-184: 名字:王大俠 年齡:100

子線程也拿到了!看源碼:

 public class InheritableThreadLocal<T> extends ThreadLocal<T> {
 public InheritableThreadLocal() { }
 protected T childValue(T parentValue) {
 return parentValue;
 }
 @Override
 Values values(Thread current) {
 return current.inheritableValues;
 }
 @Override
 Values initializeValues(Thread current) {
 return current.inheritableValues = new Values();
 }
 }

它重寫了兩個方法,都指向 Thread 的成員變量 inheritableValues,而 ThreadLocal 指向的是 localValues。那子線程為何能拿到?搜索 inheritableValues 在 Thread 類中的調用:

 private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
 ...
 // Transfer over InheritableThreadLocals.
 if (currentThread.inheritableValues != null) {
 inheritableValues = new ThreadLocal.Values(currentThread.inheritableValues);
 }
 this.group.addThread(this);
 }

create 方法在 Thread 構造時調用,若 currentThread.inheritableValues 不為空,就傳給 Values 的有參構造:

 Values(Values fromParent) {
 this.table = fromParent.table.clone();
 this.mask = fromParent.mask;
 this.size = fromParent.size;
 this.tombstones = fromParent.tombstones;
 this.maximumLoad = fromParent.maximumLoad;
 this.clean = fromParent.clean;
 inheritValues(fromParent);
 }

可見它把父線程的 inheritableValues 完整複製了過來,所以子線程能拿到保存的變量。分析到此為止,若有疏漏還請指正。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved