国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Looper Handler MessageQueue源碼解析

2019-11-09 17:52:03
字體:
供稿:網(wǎng)友

Looper Handler MessageQueue源碼解析

* class LooperThread extends Thread { * public Handler mHandler; * * public void run() { * Looper.PRepare(); * * mHandler = new Handler() { * public void handleMessage(Message msg) { * // process incoming messages here * } * }; * * Looper.loop(); * } * }

上邊為谷歌推薦的Handler使用方法,通過以上代碼 理解下Looper Handler MessageQueue相關(guān)代碼

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));//保證每個線程只有一個Looper對象 }

Looper與MessageQueue綁定:

private Looper(boolean quitAllowed) { //每個Looper唯一對應(yīng)一個MessageQueue 即一個線程對應(yīng)一個Looper 一個MessageQueue mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }

Looper自循環(huán)

public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) {//無線循環(huán) Message msg = queue.next(); // might block if (msg == null) { return; } msg.target.dispatchMessage(msg);//回調(diào)dispatchMessage方法 msg.recycleUnchecked(); } }

下面是Handler將消息添加到MessageQunue的流程:

boolean enqueueMessage(Message msg, long when) { synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException(msg.target + " sending message to a Handler on a dead thread"); msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { msg.next = p; mMessages = msg; needWake = mBlocked; } else { 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; prev.next = msg; // 最后一個p為null 將message插入到倒數(shù)第二個位置 } if (needWake) { nativeWake(mPtr); } } return true; }

以上就是Looper Handler MessageQueue實(shí)現(xiàn)線程間通信的大致邏輯~


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 衡山县| 房产| 宣武区| 宜兰市| 宝坻区| 泰州市| 平江县| 西宁市| 哈巴河县| 怀化市| 铅山县| 微山县| 张掖市| 多伦县| 河间市| 卓资县| 三门县| 济阳县| 滨州市| 汤原县| 通化市| 深泽县| 盈江县| 梁山县| 贵阳市| 申扎县| 登封市| 大田县| 昭觉县| 科技| 区。| 沙雅县| 河西区| 积石山| 黔西| 衡山县| 张掖市| 安泽县| 郸城县| 新安县| 惠东县|