一.PriorityQueue優(yōu)先級隊(duì)列
在講Handler之前,先講一下優(yōu)先級隊(duì)列,在Java中具體呈現(xiàn)的類是PriorityQueue,其實(shí)現(xiàn)了Queue接口,延展一下Java的集合
Queue以及Deque都是繼承于Collection遣疯,Deque是Queue的子接口。Deque是double ended queue凿傅,我將其理解成雙端結(jié)束的隊(duì)列缠犀,雙端隊(duì)列,可以在首尾插入或刪除元素聪舒。而Queue的解釋中辨液,Queue就是簡單的FIFO隊(duì)列。所以在概念上來說箱残,Queue是FIFO的單端隊(duì)列滔迈,Deque是雙端隊(duì)列。
PriorityQueue類被辑,Java給出的解釋如下:
它是基于優(yōu)先級堆的無邊界(這里講的無邊界的含義是指可自動擴(kuò)容集合長度)優(yōu)先級隊(duì)列燎悍,優(yōu)先級隊(duì)列中眾多元素的排列,要么基于它天然的排序性(即實(shí)現(xiàn)Comparable接口的類盼理,若插入的類未實(shí)現(xiàn)該接口會報(bào)類型轉(zhuǎn)換錯(cuò)誤)谈山,要么就是基于在構(gòu)造函數(shù)傳入的Comparator比較器
offer進(jìn)棧源碼如下:
transient Object[] queue;
public boolean offer(E e) {
if (e == null)
throw new NullPointerException();
modCount++;
int i = size;
if (i >= queue.length)
grow(i + 1);
size = i + 1;
if (i == 0)
queue[0] = e;
else
siftUp(i, e);
return true;
}
private void siftUp(int k, E x) {
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
}
private void siftUpComparable(int k, E x) {
Comparable<? super E> key = (Comparable<? super E>) x;
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = queue[parent];
if (key.compareTo((E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
queue[k] = key;
}
private void siftUpUsingComparator(int k, E x) {
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = queue[parent];
if (comparator.compare(x, (E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
queue[k] = x;
}
大概如下:優(yōu)先級隊(duì)列內(nèi)部用數(shù)組實(shí)現(xiàn),在插入元素時(shí)宏怔,會先擴(kuò)容數(shù)組大小加1奏路,然后通過排序方法將該元素插入指定位置中
poll出棧源碼如下:
public E poll() {
if (size == 0)
return null;
int s = --size;
modCount++;
E result = (E) queue[0];
E x = (E) queue[s];
queue[s] = null;
if (s != 0)
siftDown(0, x);
return result;
}
出棧既是將數(shù)組第一個(gè)元素刪除,但這里不會講數(shù)組大小減1臊诊,而且將數(shù)組最后一個(gè)位置置為null鸽粉,并將數(shù)組1-size-1的所有元素前置1位。
以上就是優(yōu)先級隊(duì)列的概念
二.Handler機(jī)制
- Handler:用來發(fā)送消息:sendMessage等多個(gè)方法抓艳,并實(shí)現(xiàn)handleMessage()方法處理回調(diào)(還可以使用Message或Handler的Callback進(jìn)行回調(diào)處理)触机。
- Message:消息實(shí)體,發(fā)送的消息即為Message類型。
- MessageQueue:消息隊(duì)列威兜,用于存儲消息销斟。發(fā)送消息時(shí),消息入隊(duì)列椒舵,然后Looper會從這個(gè)MessageQueen取出消息進(jìn)行處理。
- Looper:與線程綁定约谈,不僅僅局限于主線程笔宿,綁定的線程用來處理消息。loop()方法是一個(gè)死循環(huán)棱诱,一直從MessageQueen里取出消息進(jìn)行處理泼橘。
Handler機(jī)制本身就是基于生產(chǎn)者與消費(fèi)者模型,發(fā)送消息的線程是生產(chǎn)者迈勋,處理消息的線程是消費(fèi)者(即send/post是生產(chǎn)線程炬灭,handleMessage的是消費(fèi)線程)。其工作流程如下:
Handler有各類的send方法靡菇,和post方法重归,其最終都會執(zhí)行MessageQueue類中enqueueMessage()方法,在入棧這些消息執(zhí)行厦凤,消息本身會有處理時(shí)間即when屬性鼻吮,比如sendMessage(msg)方法的Message的when是系統(tǒng)當(dāng)前時(shí)間,sendMessageDelayed方法的when是系統(tǒng)當(dāng)前時(shí)間加上延遲時(shí)間较鼓;隨后將Message入棧到MessageQueue椎木,就是基于優(yōu)先級隊(duì)列的概念,會按照Message的when屬性進(jìn)行排序博烂,最近的Message在前面香椎,最晚的Message在后面。
Handler類中post一個(gè)線程其實(shí)就是send一個(gè)Message禽篱,callback屬性就是該線程
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
MessageQueue類中enqueueMessage方法源碼如下:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
這邊Handler將Message置于MessageQueue中畜伐,那邊Looper的loop方法正在不停從MessageQueue中消費(fèi)Message,Loop類中l(wèi)oop方法源碼如下:
Loop類:
public static void loop() {
final MessageQueue queue = me.mQueue;
for (;;) {
.................
Message msg = queue.next();
.................
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
.................
}
}
MessageQueue類:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
以上源碼可知,loop會不斷的問MessageQueue中是否有可處理的Message谆级,判斷可處理的依據(jù)是系統(tǒng)當(dāng)前時(shí)間是否大于等于Message的when屬性烤礁,如果符合現(xiàn)將此message在MessageQueue隊(duì)列中移除,之后return回去肥照。如果不符合則阻塞線程脚仔,調(diào)用nativePollOnce方法,阻塞時(shí)間為nextPollTimeoutMillis舆绎;當(dāng)loop有處理的message時(shí)鲤脏,就會交給Handler進(jìn)行dispatch分發(fā)消息
Hander中Looper相關(guān)
Looper的獲取是通過ThreadLocal的get操作,其set操作是在Looper的prepare方法中,會實(shí)例化一個(gè)Looper猎醇,并將此對象存儲在ThreadLocal中(由此可以看出looper的prepare方法只做looper對象的線程存儲操作)
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
一個(gè)線程可以有N個(gè)Handler,但是只有一個(gè)Looper窥突,如何保證Looper的唯一性,就是通過ThreadLocal,其使用使用很簡單硫嘶,如下
static final ThreadLocal<T> sThreadLocal = new ThreadLocal<T>();
sThreadLocal.set()
sThreadLocal.get()
其中set,get源碼如下:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
由源碼可知阻问,ThreadLocal本身實(shí)現(xiàn)很簡單,是由ThreadLocalMap這么一個(gè)鍵值對Map來實(shí)現(xiàn)當(dāng)前線程內(nèi)存儲變量的能力沦疾。有set源碼可知称近,Looper的實(shí)例對象會存儲在ThreadLocalMap中,其鍵為ThreadLocal對象本身哮塞;而ThreadLocalMap的獲取是通過getMap方法刨秆,getMap方法源碼如下:
ThreadLocal類:
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
Thread類:
public class Thread implements Runnable {
ThreadLocal.ThreadLocalMap threadLocals = null;
}
由ThreadLocalMap相關(guān)源碼可知,ThreadLocalMap類的對象threadLocals是單個(gè)線程唯一的忆畅,looper的獲取是基于threadLocal的衡未,所以Looper是單個(gè)線程唯一的。
我們平時(shí)用的實(shí)例化的Handler都是基于主線程的家凯,子線程如何實(shí)例化Handler呢缓醋?
要注意的幾點(diǎn)如下:
- Looper.prepare (實(shí)例化Looper,并存儲至ThreadLocal中)
- Looper.loop (啟動for循環(huán))
- Looper.quit (停止loop的for循環(huán)肆饶,釋放線程改衩、釋放內(nèi)存)
public class HandlerDemoThread extends Thread {
private Looper mLooper;
@Override
public void run() {
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
}
Looper.loop();
}
public Looper getLooper() throws Exception {
if (!isAlive()) {
throw new Exception("current thread is not alive");
}
if (mLooper == null) {
throw new Exception("current thread is not start");
}
return mLooper;
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val handlerThread = HandlerDemoThread()
handlerThread.start()
val handler1 = object : Handler(handlerThread.getLooper()) {
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
}
}
handler1.sendMessage(Message.obtain())
}
override fun onDestroy() {
super.onDestroy()
handler1.looper.quit()
}
}
由上述Handler系統(tǒng)源碼可知,handler在初始化前驯镊,要確保當(dāng)前線程prepare過葫督,即實(shí)例化Looper存儲與ThreadLocal中。還要啟動Looper的loop方法板惑,讓傳輸帶運(yùn)轉(zhuǎn)起來橄镜。這里有一點(diǎn)需要注意,由于send##,pos##方法可能會執(zhí)行在不同線程中冯乘,在send一個(gè)delay消息時(shí)洽胶,由于在enqueueMessage時(shí),會加同步鎖裆馒,這樣會導(dǎo)致delay算出來的時(shí)間是不準(zhǔn)確的姊氓;在這里大家還要注意到,平時(shí)實(shí)例化主線程的Handler的時(shí)候喷好,是不需要調(diào)用當(dāng)前主線程的prepare與loop方法翔横,這是因?yàn)锳ctivityThread已經(jīng)啟動過主線程的Looper。
ActivityThread就是我們常說的主線程或UI線程梗搅,ActivityThread的main方法是整個(gè)APP的入口禾唁,
ActivityThread的main方法源碼如下:
public static void main(String[] args) {
...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
//在attach方法中會完成Application對象的初始化效览,然后調(diào)用Application的onCreate()方法
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
為何主線程不用調(diào)用quit方法,當(dāng)然邏輯就是不行的荡短,主線程關(guān)了丐枉,那app就關(guān)閉了。而且在quit方法中掘托,即最終調(diào)用的是MessageQueue的quit方法瘦锹,已經(jīng)做了驗(yàn)證,源碼如下:
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
removeAllMessagesLocked();
} else {
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}
Message類:
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
MessageQueue的quit方法闪盔,源碼可知是釋放掉消息隊(duì)列的所有Message沼本,以及釋放Message內(nèi)部參數(shù),即釋放內(nèi)存锭沟。同時(shí)將全局變量mQuitting置為true,通過nativeWake再喚醒線程识补,由于Looper中l(wèi)oop不停在調(diào)用MessageQueue類的next方法族淮,其中next方法部分源碼如下:
.................
for (;;) {
.................
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
.................
if (mQuitting) {
dispose();
return null;
}
.................
}
}
由于MessageQueue的quit已喚醒線程,所以next會一直往下走凭涂,遇到mQuitting為true祝辣,變回diapose,同時(shí)返回null切油,loop那邊拿到null后蝙斜,變回直接return loop方法。loop方法便會結(jié)束澎胡,整個(gè)線程便會得要釋放孕荠。所以回到quit方法,所以quit既能釋放內(nèi)存攻谁,也釋放了線程稚伍;
在子線程中,如果手動為其創(chuàng)建了Looper戚宦,那么在所有的事情完成以后應(yīng)該調(diào)用quit方法來終止消息循環(huán)个曙,否則這個(gè)子線程就會一直處于等待(阻塞)狀態(tài),而如果退出Looper以后受楼,這個(gè)線程就會立刻(執(zhí)行所有方法并)終止垦搬,因此建議不需要的時(shí)候終止Looper。即調(diào)用quit方法
這里要注意的一點(diǎn)是艳汽,recycleUnchecked方法中猴贰,有這么一段代碼:
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
這里的邏輯是:從隊(duì)尾將該已被內(nèi)部清空,外部去除關(guān)聯(lián)的Message骚灸,添加至消息池里糟趾。消息池就是用戶創(chuàng)建Message的內(nèi)存池。那Handler中如何創(chuàng)建消息呢?為了防止頻繁實(shí)例化Message义郑,從而引發(fā)內(nèi)存抖動蝶柿,這里就用到內(nèi)存共享,即內(nèi)存復(fù)用的概念非驮。即調(diào)用Message中obtain方法交汤,來獲取Message實(shí)例,obtain方法源碼如下:
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
思考:為什么Handler不會阻塞主線程劫笙?
從以上分析可知芙扎,Handler在處理消息時(shí),對于未到處理時(shí)間的隊(duì)頭Message填大,便會休眠掉進(jìn)棧的當(dāng)前線程戒洼,直到休眠時(shí)間結(jié)束,才會去處理隊(duì)頭Message允华。既然會休眠線程圈浇,為什么Handler沒有阻塞主線程呢?
對于線程即是一段可執(zhí)行的代碼靴寂,當(dāng)可執(zhí)行代碼執(zhí)行完成后磷蜀,線程生命周期便該終止了,線程退出百炬。而對于主線程褐隆,我們是絕不希望會被運(yùn)行一段時(shí)間,自己就退出剖踊,那么如何保證能一直存活呢庶弃?簡單做法就是可執(zhí)行代碼是能一直執(zhí)行下去的,死循環(huán)便能保證不會被退出(eg:binder線程也是采用死循環(huán)的方法蜜宪,通過循環(huán)方式不同與Binder驅(qū)動進(jìn)行讀寫操作)虫埂,當(dāng)然并非簡單地死循環(huán),無消息時(shí)會休眠圃验。但這里可能又引發(fā)了另一個(gè)問題掉伏,既然是死循環(huán)又如何去處理其他事務(wù)呢?通過創(chuàng)建新線程的方式澳窑。真正會卡死主線程的操作是在回調(diào)方法onCreate/onStart/onResume等操作時(shí)間過長斧散,會導(dǎo)致掉幀,甚至發(fā)生ANR摊聋,looper.loop本身不會導(dǎo)致應(yīng)用卡死鸡捐。
這里便會再度引發(fā)一個(gè):主線程的死循環(huán)一直運(yùn)行是不是特別消耗CPU資源呢?
當(dāng)然不會麻裁,MessageQueue沒有消息時(shí)箍镜,便阻塞在loop的queue.next()中的nativePollOnce()方法里源祈,此時(shí)主線程會釋放CPU資源進(jìn)入休眠狀態(tài),直到下個(gè)消息到達(dá)或者有事務(wù)發(fā)生色迂,通過往pipe管道寫端寫入數(shù)據(jù)來喚醒主線程工作香缺。這里采用的epoll機(jī)制,是一種IO多路復(fù)用機(jī)制歇僧,可以同時(shí)監(jiān)控多個(gè)描述符图张,當(dāng)某個(gè)描述符就緒(讀或?qū)懢途w),則立刻通知相應(yīng)程序進(jìn)行讀或?qū)懖僮髡┖罚举|(zhì)同步I/O祸轮,即讀寫是阻塞的。 所以說侥钳,主線程大多數(shù)時(shí)候都是處于休眠狀態(tài)适袜,并不會消耗大量CPU資源。