常見在主線程(UI線程)更新UI。
public class MainActivity extends Activity {
private Handler handler = new Handler() {
// 處理子線程給我們發(fā)送的消息亮元。
//注意:handler并沒有處理耗時操作的能力舟山,使用handler的目的只是完成耗時操作以后,給個通知(帶個數(shù)據(jù))去觸發(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方法中完成網(wǎng)絡(luò)耗時的操作
@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的目的只是完成耗時操作以后,給個通知(帶些數(shù)據(jù))去觸發(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)已經(jīng)自動幫我們調(diào)用了Looper.prepare()方法.
如果沒有Looper.prepare()的話蘑志,會拋異常:"Can't create handler inside thread that has not called Looper.prepare()"累奈。
一步一步分析:
1.先介紹ThreadLoacal和Thread的關(guān)系:
- 通常情況下,我們創(chuàng)建的變量是可以被任何一個線程訪問并修改的急但。而使用ThreadLocal創(chuàng)建的變量只能被當前線程訪問澎媒,其他線程則無法訪問和修改。
- TheadLocal類中定義了一個ThreadLocalMap類波桩,ThreadLocalMap類中定義了一個Entry類戒努,并且有一個長度為16的Entry數(shù)組。Entry類每次把ThreadLocal的實例和對應值保存起來镐躲,Entry不是map储玫,只是維護了一個key-value的值。
- Thead類中萤皂,有一個ThreadLocalMap類的引用撒穷。也就是每個線程,能保存16個ThreadLocal實例和值的對應關(guān)系裆熙。
- 資料
//ThreadLocal類端礼,看set方法如何給thread設(shè)置對應值
//value就是傳入的要和Thread對應的值,例如:Looper對象入录。
public void set(T value) {
Thread t = Thread.currentThread();
//獲得該thread中的map對象
ThreadLocalMap map = getMap(t);
//拿到Thread中的map對象蛤奥,把要對應的值設(shè)置到map中。實際上僚稿,是設(shè)置到了map中的Entry類中凡桥。
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
//拿到的是當前thread中的map對象
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//當前Thread如果沒有的話,就設(shè)置一個新的map
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
//每個ThreadLocalMap生成實例的時候贫奠,初始化一個長度為16的Entry數(shù)組唬血。
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;
}
//實際上對應的值望蜡,設(shè)置到了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設(shè)置值的流程是:在thread拿到或生成新的 threadLocalMap,以threadLoacal的hash值作為腳標找到Entry拷恨,設(shè)置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,沒有設(shè)置過對應值冕杠。這給Thread設(shè)置個map微姊,返回null。
/**
*看下面方法分预,Looper.preaper()方法兢交,調(diào)用了set設(shè)置對應的Looper。
*所以笼痹,沒有調(diào)用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值作為腳標找到數(shù)組中對應的Entry晴裹,取出value毙石。
總的來說败徊,通過ThreadLocal獲取/設(shè)置Thread的對應值的流程為:thread拿到或生成threadLocalMap蝙斜,通過threadLocal的hash值(不知道是什么的hashCode)對應的腳標经磅,生成Entry放入對應值到value泌绣,Entry放入數(shù)組。
Entry中key相當于是threadLocal的實例對象预厌,且是弱引用赞别。沒研究具體原理。
2.先看有preaper()時配乓,為什么new Handler()能得到Looper對象』莼伲看看preaper()做了什么:
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//設(shè)置Looper到Thread
sThreadLocal.set(new Looper(quitAllowed));
}
//ThreadLocal的set方法犹芹,把looper設(shè)置到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設(shè)置到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中已經(jīng)有了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類加載的時候就已經(jīng)存在了。無論哪個線程訪問Looper中的threadLocal都是該變量低矮。
//另外:泛型類印叁,已經(jīng)聲明為Looper,也就是set/get確定操作的對應值為Looper類军掂。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
所以轮蜕,不同的線程,操作Looper.prepear,都是在各自的線程set/get操作Looper蝗锥,互不干擾跃洛。