1.Handler初始化

資料1
資料2
資料3
資料4

常見在主線程(UI線程)更新UI。

public class MainActivity extends Activity {  
    private Handler handler = new Handler() {  
        // 處理子線程給我們發(fā)送的消息。
        //注意:handler并沒有處理耗時操作的能力,使用handler的目的只是完成耗時操作以后,給個通知(帶個數據)去觸發(fā)下面的操作。
        @Override  
        public void handleMessage(android.os.Message msg) {  
            byte[] data = (byte[])msg.obj;  
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  
            imageView.setImageBitmap(bitmap);  
        };  
    };  
  
    public class MyThread implements Runnable{  
        // 在run方法中完成網絡耗時的操作  
        @Override  
        public void run() {  
                    byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());  
                    // 耗時操作是另外一個線程,和主線程是異步的,想讓主線成知道你什么時候完成了操作,用handler通知主線程。
                    // 注意:這個msg的目的時通知主線程的handler,所以必須用主線程的handler發(fā)送信息,而不是new出來的handler。
                    Message message = Message.obtain();  
                    message.obj = data;  
                    message.what = DOWNLOAD_IMG;  
                    handler.sendMessage(message);  
        }  
          
    }  
}  

注意:handler并沒有處理耗時操作的能力,使用handler的目的只是完成耗時操作以后,給個通知(帶些數據)去觸發(fā)下面的操作。

在子線程中 new Handler()

    //Google推薦寫法。其它寫法我特么也不知道啊。
   class LooperThread extends Thread { 
       public Handler mHandler; 
       public void run() { 
       
          Looper.prepare(); 
          
          mHandler = new Handler() { 
              public void handleMessage(Message msg) { 
                  // 處理hander信息
              } 
          }; 
          
          Looper.loop(); 
       } 
   } 

在Activity中生成的handler沒有prepare是因為:UI線程是主線程,系統(tǒng)已經自動幫我們調用了Looper.prepare()方法.

如果沒有Looper.prepare()的話,會拋異常:"Can't create handler inside thread that has not called Looper.prepare()"。
一步一步分析:

1.先介紹ThreadLoacal和Thread的關系:

  • 通常情況下,我們創(chuàng)建的變量是可以被任何一個線程訪問并修改的。而使用ThreadLocal創(chuàng)建的變量只能被當前線程訪問,其他線程則無法訪問和修改。
  • TheadLocal類中定義了一個ThreadLocalMap類,ThreadLocalMap類中定義了一個Entry類,并且有一個長度為16的Entry數組。Entry類每次把ThreadLocal的實例和對應值保存起來,Entry不是map,只是維護了一個key-value的值。
  • Thead類中,有一個ThreadLocalMap類的引用。也就是每個線程,能保存16個ThreadLocal實例和值的對應關系。
  • 資料
//ThreadLocal類,看set方法如何給thread設置對應值
//value就是傳入的要和Thread對應的值,例如:Looper對象。
public void set(T value) {
        Thread t = Thread.currentThread();
        //獲得該thread中的map對象
        ThreadLocalMap map = getMap(t);
        //拿到Thread中的map對象,把要對應的值設置到map中。實際上,是設置到了map中的Entry類中。
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
//拿到的是當前thread中的map對象    
ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
//當前Thread如果沒有的話,就設置一個新的map    
void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
//每個ThreadLocalMap生成實例的時候,初始化一個長度為16的Entry數組。
ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
            table = new Entry[16];
            //threadLocal作為腳標
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
        }
//實際上對應的值,設置到了Entry的value屬性上
static class Entry extends WeakReference<ThreadLocal> {
            /** The value associated with this ThreadLocal. */
            Object value;
            Entry(ThreadLocal k, Object v) {
                super(k);
                value = v;
            }
        }

通過ThreadLoacal給Thread設置值的流程是:在thread拿到或生成新的 threadLocalMap,以threadLoacal的hash值作為腳標找到Entry,設置value。

//再看ThreadLoacal的get方法。
public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
        //獲得當前thread中map對象的entry對象的value屬性,即存入的對應值。
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        //如果e == null,沒有設置過對應值。這給Thread設置個map,返回null。
        /**
        *看下面方法,Looper.preaper()方法,調用了set設置對應的Looper。
        *所以,沒有調用Looper.preaper()時,new Handler()中mLooper = Looper.myLooper()-->sThreadLocal.get()得到的是null。
        */
        return setInitialValue();
    }
    
private T setInitialValue() {
        T value = null;
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

通過ThreadLocal獲得Thread對應值流程:在thread拿到map,已threadLocal的hash值作為腳標找到數組中對應的Entry,取出value。

總的來說,通過ThreadLocal獲?。O置Thread的對應值的流程為:thread拿到或生成threadLocalMap,通過threadLocal的hash值(不知道是什么的hashCode)對應的腳標,生成Entry放入對應值到value,Entry放入數組。

Entry中key相當于是threadLocal的實例對象,且是弱引用。沒研究具體原理。

2.先看有preaper()時,為什么new Handler()能得到Looper對象??纯磒reaper()做了什么:

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //設置Looper到Thread
        sThreadLocal.set(new Looper(quitAllowed));
    }
//ThreadLocal的set方法,把looper設置到thread中的map對象中。
public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

3.沒有preaper()時

 public Handler(Callback callback, boolean async) {
        mLooper = Looper.myLooper();
        //這里得到null,所以報錯。
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
    
    //Looper里的方法
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
    
    //ThreadLocal里的方法
    //沒有preaper把looper設置到thread中的map的entry中,所以得到的value為null。
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }
    private T setInitialValue() {
        T value = null;
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

Thread,Looper,MessageQueue三者一一對應:

1.如果Thread中已經有了Looper對象,再preaper的時候,!=null會報錯。一個Looper只能對應一個Thread。
2.MessageQueue在Looper中,Looper在Thread的map對象中。

為什么說使用ThreadLocal創(chuàng)建的變量只能被當前線程訪問,其他線程則無法訪問和修改呢?

既然這個map是Thread自己的,又可以被外界訪問,為什么不能被其它線程修改?threadLocalMap只是Thread中的一個變量,是可以修改的。只是說,不同的線程,同一個threadLocal對象,操作set/get方法時,各個線程只能修改自己的那一份value對應值。
例如:
//Looper中,sThreadLocal是一個static 并且final的變量,從Looper類加載的時候就已經存在了。無論哪個線程訪問Looper中的threadLocal都是該變量。
//另外:泛型類,已經聲明為Looper,也就是set/get確定操作的對應值為Looper類。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
所以,不同的線程,操作Looper.prepear,都是在各自的線程set/get操作Looper,互不干擾。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容